@getstrata/bootstrap 0.1.1 → 0.2.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.
Files changed (95) hide show
  1. package/dist/bootstrap/context.d.ts +6 -0
  2. package/dist/bootstrap/createWebRoutes.d.ts +4 -0
  3. package/dist/bootstrap/discoverListeners.d.ts +5 -0
  4. package/dist/bootstrap/discoverModules.d.ts +4 -0
  5. package/dist/bootstrap/env.d.ts +9 -0
  6. package/dist/bootstrap/httpKernel.d.ts +2 -0
  7. package/dist/bootstrap/listeners/invalidateCacheOnModelWrite.d.ts +3 -0
  8. package/dist/bootstrap/modules.d.ts +1 -0
  9. package/dist/bootstrap/providers/auth.d.ts +3 -0
  10. package/dist/bootstrap/providers/cache.d.ts +3 -0
  11. package/dist/bootstrap/providers/config.d.ts +5 -0
  12. package/dist/bootstrap/providers/events.d.ts +5 -0
  13. package/dist/bootstrap/providers/index.d.ts +3 -0
  14. package/dist/bootstrap/providers/listeners.d.ts +3 -0
  15. package/dist/bootstrap/providers/policy.d.ts +3 -0
  16. package/dist/bootstrap/providers/queue.d.ts +3 -0
  17. package/dist/bootstrap/providers/view.d.ts +5 -0
  18. package/dist/bootstrap/public-api.d.ts +7 -1
  19. package/dist/bootstrap/routeRegistry.d.ts +14 -0
  20. package/dist/bootstrap/schedule.d.ts +1 -0
  21. package/dist/bootstrap/secretsGuard.d.ts +2 -0
  22. package/dist/cli/commands/scheduleRun.d.ts +3 -0
  23. package/dist/config/auth.d.ts +7 -0
  24. package/dist/config/queue.d.ts +8 -0
  25. package/dist/config/rateLimit.d.ts +2 -1
  26. package/dist/core/audit/exportAuditLogs.d.ts +8 -0
  27. package/dist/core/audit/siemFormatter.d.ts +30 -0
  28. package/dist/core/auth/sessionCookie.d.ts +6 -0
  29. package/dist/core/auth/sessionGuard.d.ts +9 -0
  30. package/dist/core/cache/createCacheStore.d.ts +11 -0
  31. package/dist/core/cache/modelCacheTags.d.ts +3 -0
  32. package/dist/core/cache/redisCacheStore.d.ts +23 -0
  33. package/dist/core/cache/repository.d.ts +17 -0
  34. package/dist/core/cache/simpleCache.d.ts +23 -0
  35. package/dist/core/cache/simpleCacheStore.d.ts +16 -0
  36. package/dist/core/cache/store.d.ts +12 -0
  37. package/dist/core/cache/taggedCache.d.ts +9 -0
  38. package/dist/core/config/envSchema.d.ts +12 -0
  39. package/dist/core/database/baseRepository.d.ts +16 -4
  40. package/dist/core/database/index.d.ts +10 -4
  41. package/dist/core/database/migrations/types.d.ts +15 -0
  42. package/dist/core/database/model.d.ts +57 -0
  43. package/dist/core/database/query.d.ts +25 -14
  44. package/dist/core/database/relationships.d.ts +32 -2
  45. package/dist/core/database/repositoryQuery.d.ts +16 -1
  46. package/dist/core/database/schema/blueprint.d.ts +47 -0
  47. package/dist/core/database/schema/columnDefinition.d.ts +36 -0
  48. package/dist/core/database/schema/driver.d.ts +8 -0
  49. package/dist/core/database/schema/errors.d.ts +4 -0
  50. package/dist/core/database/schema/grammars/compileStatements.d.ts +8 -0
  51. package/dist/core/database/schema/grammars/createGrammar.d.ts +4 -0
  52. package/dist/core/database/schema/grammars/grammar.d.ts +10 -0
  53. package/dist/core/database/schema/grammars/index.d.ts +7 -0
  54. package/dist/core/database/schema/grammars/mysqlGrammar.d.ts +2 -0
  55. package/dist/core/database/schema/grammars/postgresGrammar.d.ts +2 -0
  56. package/dist/core/database/schema/grammars/sqliteGrammar.d.ts +2 -0
  57. package/dist/core/database/schema/index.d.ts +12 -0
  58. package/dist/core/database/schema/schema.d.ts +21 -0
  59. package/dist/core/database/types.d.ts +39 -2
  60. package/dist/core/database/whereBuilder.d.ts +17 -0
  61. package/dist/core/jobs/dispatchWebhookJob.d.ts +14 -0
  62. package/dist/core/jobs/invalidateCacheTagsJob.d.ts +12 -0
  63. package/dist/core/pagination/index.d.ts +11 -1
  64. package/dist/core/queue/createAppQueue.d.ts +6 -0
  65. package/dist/core/queue/failedJobRepository.d.ts +6 -0
  66. package/dist/core/queue/failedJobService.d.ts +15 -0
  67. package/dist/core/queue/failedJobTable.d.ts +3 -0
  68. package/dist/core/queue/jobRegistry.d.ts +14 -0
  69. package/dist/core/queue/jobRunner.d.ts +9 -0
  70. package/dist/core/queue/publicQueue.d.ts +15 -0
  71. package/dist/core/queue/redisQueue.d.ts +29 -0
  72. package/dist/core/queue/resilientQueue.d.ts +9 -0
  73. package/dist/core/queue/types.d.ts +8 -0
  74. package/dist/core/scheduler/schedule.d.ts +15 -0
  75. package/dist/core/security/safeFetch.d.ts +8 -0
  76. package/dist/core/security/safeUrl.d.ts +5 -0
  77. package/dist/core/view/etaViewEngine.d.ts +15 -0
  78. package/dist/core/view/htmlResponse.d.ts +6 -0
  79. package/dist/core/view/index.d.ts +5 -0
  80. package/dist/core/view/viewEngine.d.ts +6 -0
  81. package/dist/core/view/webLayoutData.d.ts +17 -0
  82. package/dist/domain/scim.d.ts +9 -0
  83. package/dist/index.js +4175 -458
  84. package/dist/modules/user/apiTokenRepository.d.ts +1 -1
  85. package/dist/modules/user/apiTokenTable.d.ts +1 -1
  86. package/dist/modules/user/authService.d.ts +1 -1
  87. package/dist/modules/user/notificationRepository.d.ts +1 -1
  88. package/dist/modules/user/notificationService.d.ts +1 -1
  89. package/dist/modules/user/notificationTable.d.ts +1 -1
  90. package/dist/modules/user/oauthIdentityRepository.d.ts +2 -2
  91. package/dist/modules/user/provider.d.ts +1 -1
  92. package/dist/modules/user/repository.d.ts +1 -1
  93. package/dist/modules/user/table.d.ts +1 -1
  94. package/dist/modules/user/tokenService.d.ts +1 -1
  95. package/package.json +44 -3
package/dist/index.js CHANGED
@@ -1,4 +1,407 @@
1
1
  // @bun
2
+ // ../../src/core/scheduler/schedule.ts
3
+ class Schedule {
4
+ tasks = [];
5
+ command(expression, name, run) {
6
+ this.tasks.push({ expression, name, run });
7
+ return this;
8
+ }
9
+ dueTasks(now = new Date) {
10
+ const minute = now.getMinutes();
11
+ return this.tasks.filter((task) => {
12
+ if (task.expression === "* * * * *") {
13
+ return true;
14
+ }
15
+ if (task.expression.startsWith("*/")) {
16
+ const interval = Number.parseInt(task.expression.slice(2), 10);
17
+ return Number.isInteger(interval) && interval > 0 && minute % interval === 0;
18
+ }
19
+ return false;
20
+ });
21
+ }
22
+ tasksList() {
23
+ return [...this.tasks];
24
+ }
25
+ }
26
+ var appSchedule = new Schedule;
27
+ async function runDueScheduledTasks(schedule = appSchedule, now = new Date) {
28
+ const due = schedule.dueTasks(now);
29
+ for (const task of due) {
30
+ await task.run();
31
+ }
32
+ return due.length;
33
+ }
34
+
35
+ // ../../src/config/features.ts
36
+ function readFeatureFlags() {
37
+ return {
38
+ webhooks: (process.env.FEATURE_WEBHOOKS ?? "true") !== "false",
39
+ fullTextSearch: (process.env.FEATURE_SEARCH ?? "true") !== "false",
40
+ auditLog: (process.env.FEATURE_AUDIT_LOG ?? "true") !== "false",
41
+ oauthLogin: (process.env.FEATURE_OAUTH ?? "true") !== "false",
42
+ samlLogin: (process.env.FEATURE_SAML ?? "false") === "true",
43
+ scim: (process.env.FEATURE_SCIM ?? "true") !== "false",
44
+ billing: (process.env.FEATURE_BILLING ?? "true") !== "false",
45
+ siemExport: (process.env.FEATURE_SIEM_EXPORT ?? "true") !== "false",
46
+ publicReads: (process.env.FEATURE_PUBLIC_READS ?? "true") !== "false",
47
+ emailVerification: (process.env.FEATURE_EMAIL_VERIFICATION ?? "false") === "true",
48
+ mfa: (process.env.FEATURE_MFA ?? "false") === "true"
49
+ };
50
+ }
51
+ var featureFlags = readFeatureFlags();
52
+ function isFeatureEnabled(feature) {
53
+ return readFeatureFlags()[feature];
54
+ }
55
+
56
+ // ../../src/config/app.ts
57
+ var appConfig = {
58
+ name: "WorkHub",
59
+ env: process.env.APP_ENV ?? "local",
60
+ debug: (process.env.APP_DEBUG ?? "true") !== "false",
61
+ url: process.env.APP_URL ?? "http://localhost:3000",
62
+ apiPrefix: process.env.API_PREFIX ?? "/api/v1"
63
+ };
64
+
65
+ // ../../src/config/database.ts
66
+ function readInteger(name, fallback) {
67
+ const parsed = Number.parseInt(process.env[name] ?? String(fallback), 10);
68
+ return Number.isInteger(parsed) && parsed >= 0 ? parsed : fallback;
69
+ }
70
+ var databaseConfig = {
71
+ url: process.env.DATABASE_URL ?? "",
72
+ poolMax: readInteger("DB_POOL_MAX", 10),
73
+ idleTimeoutSeconds: readInteger("DB_POOL_IDLE_TIMEOUT", 30),
74
+ maxLifetimeSeconds: readInteger("DB_POOL_MAX_LIFETIME", 3600),
75
+ connectionTimeoutSeconds: readInteger("DB_CONNECTION_TIMEOUT", 10)
76
+ };
77
+
78
+ // ../../src/core/database/connectionContext.ts
79
+ import { AsyncLocalStorage } from "async_hooks";
80
+ var activeConnection = new AsyncLocalStorage;
81
+ function runWithDatabaseConnection(connection, callback) {
82
+ return activeConnection.run(connection, callback);
83
+ }
84
+ function getActiveDatabaseConnection(fallback) {
85
+ return activeConnection.getStore() ?? fallback;
86
+ }
87
+
88
+ // ../../src/db/connection/createConnection.ts
89
+ var {SQL } = globalThis.Bun;
90
+ function createDatabaseConnection(config) {
91
+ if (!config.url) {
92
+ throw new Error("DATABASE_URL is not configured. Set DATABASE_URL before starting the app or running integration tests.");
93
+ }
94
+ return new SQL({
95
+ url: config.url,
96
+ max: config.poolMax,
97
+ idleTimeout: config.idleTimeoutSeconds,
98
+ maxLifetime: config.maxLifetimeSeconds,
99
+ connectionTimeout: config.connectionTimeoutSeconds
100
+ });
101
+ }
102
+
103
+ // ../../src/db/connection/index.ts
104
+ var connectionHolder = {
105
+ connection: null
106
+ };
107
+ function getDatabase() {
108
+ if (!connectionHolder.connection) {
109
+ connectionHolder.connection = createDatabaseConnection(databaseConfig);
110
+ }
111
+ return connectionHolder.connection;
112
+ }
113
+ var POOL_CONNECTION_METHODS = new Set(["begin", "close", "connect"]);
114
+ function resolveDatabase() {
115
+ return getActiveDatabaseConnection(getDatabase());
116
+ }
117
+ function resolveDatabaseForProperty(property) {
118
+ if (typeof property === "string" && POOL_CONNECTION_METHODS.has(property)) {
119
+ return getDatabase();
120
+ }
121
+ return resolveDatabase();
122
+ }
123
+ var db = new Proxy(function database() {}, {
124
+ apply(_target, _thisArg, args) {
125
+ return resolveDatabase()(...args);
126
+ },
127
+ get(_target, property) {
128
+ const connection = resolveDatabaseForProperty(property);
129
+ const value = connection[property];
130
+ return typeof value === "function" ? value.bind(connection) : value;
131
+ }
132
+ });
133
+ var connection_default = db;
134
+
135
+ // ../../src/core/security/safeFetch.ts
136
+ var DEFAULT_FETCH_TIMEOUT_MS = 1e4;
137
+ async function safeFetch(input, init = {}, options = {}) {
138
+ const timeoutMs = options.timeoutMs ?? DEFAULT_FETCH_TIMEOUT_MS;
139
+ const maxRedirects = options.maxRedirects ?? 0;
140
+ const controller = new AbortController;
141
+ const timeout = setTimeout(() => controller.abort(), timeoutMs);
142
+ try {
143
+ let currentUrl = input;
144
+ let redirectCount = 0;
145
+ while (true) {
146
+ const response = await fetch(currentUrl, {
147
+ ...init,
148
+ signal: controller.signal,
149
+ redirect: "manual"
150
+ });
151
+ if (response.status >= 300 && response.status < 400) {
152
+ const location = response.headers.get("location");
153
+ if (!location || redirectCount >= maxRedirects) {
154
+ return response;
155
+ }
156
+ currentUrl = new URL(location, currentUrl).toString();
157
+ redirectCount += 1;
158
+ continue;
159
+ }
160
+ return response;
161
+ }
162
+ } finally {
163
+ clearTimeout(timeout);
164
+ }
165
+ }
166
+
167
+ // ../../src/core/errors/http.ts
168
+ class HttpError extends Error {
169
+ status;
170
+ details;
171
+ constructor(status, message, details) {
172
+ super(message);
173
+ this.name = new.target.name;
174
+ this.status = status;
175
+ this.details = details;
176
+ }
177
+ }
178
+
179
+ class BadRequestError extends HttpError {
180
+ constructor(message = "Bad Request", details) {
181
+ super(400, message, details);
182
+ }
183
+ }
184
+ class ConflictError extends HttpError {
185
+ constructor(message = "Conflict", details) {
186
+ super(409, message, details);
187
+ }
188
+ }
189
+
190
+ class UnprocessableEntityError extends HttpError {
191
+ constructor(message = "Unprocessable Entity", details) {
192
+ super(422, message, details);
193
+ }
194
+ }
195
+ class ForbiddenError extends HttpError {
196
+ constructor(message = "Forbidden", details) {
197
+ super(403, message, details);
198
+ }
199
+ }
200
+
201
+ class UnauthorizedError extends HttpError {
202
+ constructor(message = "Unauthorized", details) {
203
+ super(401, message, details);
204
+ }
205
+ }
206
+
207
+ class PayloadTooLargeError extends HttpError {
208
+ constructor(message = "Payload Too Large", details) {
209
+ super(413, message, details);
210
+ }
211
+ }
212
+
213
+ // ../../src/core/security/safeUrl.ts
214
+ var BLOCKED_HOSTNAMES = new Set([
215
+ "localhost",
216
+ "127.0.0.1",
217
+ "0.0.0.0",
218
+ "::1",
219
+ "metadata.google.internal"
220
+ ]);
221
+ function isPrivateIpv4(hostname) {
222
+ const match = /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/.exec(hostname);
223
+ if (!match) {
224
+ return false;
225
+ }
226
+ const octets = match.slice(1, 5).map((part) => Number.parseInt(part, 10));
227
+ if (octets.some((octet) => octet < 0 || octet > 255)) {
228
+ return true;
229
+ }
230
+ const [a = 0, b = 0] = octets;
231
+ if (a === 10) {
232
+ return true;
233
+ }
234
+ if (a === 127) {
235
+ return true;
236
+ }
237
+ if (a === 0) {
238
+ return true;
239
+ }
240
+ if (a === 169 && b === 254) {
241
+ return true;
242
+ }
243
+ if (a === 172 && b >= 16 && b <= 31) {
244
+ return true;
245
+ }
246
+ if (a === 192 && b === 168) {
247
+ return true;
248
+ }
249
+ return false;
250
+ }
251
+ function isBlockedHostname(hostname) {
252
+ const normalized = hostname.trim().toLowerCase();
253
+ if (normalized.length === 0) {
254
+ return true;
255
+ }
256
+ if (BLOCKED_HOSTNAMES.has(normalized)) {
257
+ return true;
258
+ }
259
+ if (normalized.endsWith(".local") || normalized.endsWith(".internal")) {
260
+ return true;
261
+ }
262
+ if (normalized.includes(":")) {
263
+ return true;
264
+ }
265
+ return isPrivateIpv4(normalized);
266
+ }
267
+ function assertSafeOutboundUrl(rawUrl, options = {}) {
268
+ let parsed;
269
+ try {
270
+ parsed = new URL(rawUrl);
271
+ } catch {
272
+ throw new BadRequestError("Webhook URL is invalid.");
273
+ }
274
+ if (parsed.protocol !== "https:" && !(options.allowHttp && parsed.protocol === "http:")) {
275
+ throw new BadRequestError("Webhook URL must use HTTPS.");
276
+ }
277
+ if (parsed.username || parsed.password) {
278
+ throw new BadRequestError("Webhook URL must not include credentials.");
279
+ }
280
+ if (isBlockedHostname(parsed.hostname)) {
281
+ throw new BadRequestError("Webhook URL targets a blocked host.");
282
+ }
283
+ return parsed;
284
+ }
285
+
286
+ // ../../src/core/tenant/databaseTenantContext.ts
287
+ async function runWithMigrationBypass(callback) {
288
+ await connection_default`SELECT set_config('app.bypass_rls', 'true', false)`;
289
+ try {
290
+ return await callback();
291
+ } finally {
292
+ await connection_default`SELECT set_config('app.bypass_rls', 'false', false)`;
293
+ }
294
+ }
295
+
296
+ // ../../src/core/audit/siemFormatter.ts
297
+ function formatSiemAuditEvent(input) {
298
+ return {
299
+ timestamp: input.created_at.toISOString(),
300
+ event_type: "workhub.audit",
301
+ actor_user_id: input.user_id,
302
+ tenant_id: input.tenant_id ?? null,
303
+ trace_id: input.trace_id ?? null,
304
+ action: input.action,
305
+ subject_type: input.subject_type,
306
+ subject_id: input.subject_id,
307
+ ip_address: input.ip_address ?? null,
308
+ user_agent: input.user_agent ?? null,
309
+ checksum: input.checksum ?? null,
310
+ payload: input.payload ?? {}
311
+ };
312
+ }
313
+ function formatCefLine(event) {
314
+ const extension = [
315
+ `rt=${event.timestamp}`,
316
+ `suid=${event.actor_user_id ?? "unknown"}`,
317
+ `cs1=${event.action}`,
318
+ `cs1Label=Action`,
319
+ `cs2=${event.subject_type}`,
320
+ `cs2Label=SubjectType`,
321
+ `cs3=${event.subject_id ?? ""}`,
322
+ `cs3Label=SubjectId`,
323
+ `src=${event.ip_address ?? ""}`,
324
+ `request=${event.trace_id ?? ""}`
325
+ ].join(" ");
326
+ return `CEF:0|WorkHub|API|1.0|${event.action}|${event.subject_type}|5|${extension}`;
327
+ }
328
+
329
+ // ../../src/core/audit/exportAuditLogs.ts
330
+ function resolveAuditExportConfig() {
331
+ const endpoint = process.env.SIEM_EXPORT_URL?.trim();
332
+ if (!endpoint) {
333
+ return null;
334
+ }
335
+ assertSafeOutboundUrl(endpoint, { allowHttp: appConfig.env !== "production" });
336
+ const batchSize = Number(process.env.SIEM_EXPORT_BATCH_SIZE ?? "100");
337
+ return {
338
+ endpoint,
339
+ format: process.env.SIEM_EXPORT_FORMAT === "cef" ? "cef" : "json",
340
+ batchSize: Number.isFinite(batchSize) ? batchSize : 100
341
+ };
342
+ }
343
+ async function exportPendingAuditLogs() {
344
+ const config = resolveAuditExportConfig();
345
+ if (!config) {
346
+ return 0;
347
+ }
348
+ return await runWithMigrationBypass(async () => {
349
+ const rows = await connection_default`
350
+ SELECT
351
+ id,
352
+ user_id,
353
+ action,
354
+ subject_type,
355
+ subject_id,
356
+ payload,
357
+ ip_address,
358
+ user_agent,
359
+ checksum,
360
+ tenant_id,
361
+ trace_id,
362
+ created_at
363
+ FROM audit_log
364
+ WHERE exported_at IS NULL
365
+ ORDER BY id
366
+ LIMIT ${config.batchSize}
367
+ `;
368
+ if (rows.length === 0) {
369
+ return 0;
370
+ }
371
+ const events = rows.map((row) => formatSiemAuditEvent({
372
+ action: row.action,
373
+ subject_type: row.subject_type,
374
+ subject_id: row.subject_id,
375
+ user_id: row.user_id,
376
+ tenant_id: row.tenant_id,
377
+ trace_id: row.trace_id,
378
+ ip_address: row.ip_address,
379
+ user_agent: row.user_agent,
380
+ checksum: row.checksum,
381
+ payload: row.payload,
382
+ created_at: row.created_at
383
+ }));
384
+ const body = config.format === "cef" ? events.map((event) => formatCefLine(event)).join(`
385
+ `) : JSON.stringify({ events });
386
+ const response = await safeFetch(config.endpoint, {
387
+ method: "POST",
388
+ headers: {
389
+ "content-type": config.format === "cef" ? "text/plain" : "application/json",
390
+ ...process.env.SIEM_EXPORT_TOKEN ? { authorization: `Bearer ${process.env.SIEM_EXPORT_TOKEN}` } : {}
391
+ },
392
+ body
393
+ });
394
+ if (!response.ok) {
395
+ throw new Error(`SIEM export failed with status ${response.status}.`);
396
+ }
397
+ const ids = rows.map((row) => row.id);
398
+ for (const id of ids) {
399
+ await connection_default`UPDATE audit_log SET exported_at = NOW() WHERE id = ${id}`;
400
+ }
401
+ return rows.length;
402
+ });
403
+ }
404
+
2
405
  // ../../src/core/logging/logger.ts
3
406
  class Logger {
4
407
  channel;
@@ -35,8 +438,41 @@ class Logger {
35
438
  }
36
439
  var appLogger = new Logger("app");
37
440
 
441
+ // ../../src/bootstrap/schedule.ts
442
+ appSchedule.command("* * * * *", "heartbeat", () => {
443
+ appLogger.debug("Scheduler heartbeat");
444
+ });
445
+ appSchedule.command("* * * * *", "audit-export", async () => {
446
+ if (!isFeatureEnabled("siemExport")) {
447
+ return;
448
+ }
449
+ try {
450
+ const exported = await exportPendingAuditLogs();
451
+ if (exported > 0) {
452
+ appLogger.info(`Exported ${exported} audit log entries to SIEM.`);
453
+ }
454
+ } catch (error) {
455
+ appLogger.error("Audit export failed.", { error: String(error) });
456
+ }
457
+ });
458
+
459
+ // ../../src/cli/commands/scheduleRun.ts
460
+ async function scheduleRunCommand() {
461
+ const due = appSchedule.dueTasks();
462
+ if (due.length === 0) {
463
+ console.log("No scheduled tasks due.");
464
+ return;
465
+ }
466
+ for (const task of due) {
467
+ console.log(`Running scheduled task: ${task.name}`);
468
+ }
469
+ await runDueScheduledTasks(appSchedule);
470
+ }
38
471
  // ../../src/bootstrap/config.ts
39
472
  var APP_PORT_CONFIG_KEY = "app.port";
473
+ var CACHE_TTL_MS_CONFIG_KEY = "cache.ttlMs";
474
+ var CACHE_MAX_ENTRIES_CONFIG_KEY = "cache.maxEntries";
475
+ var CACHE_DRIVER_CONFIG_KEY = "cache.driver";
40
476
  var REDIS_URL_CONFIG_KEY = "cache.redisUrl";
41
477
  var DATABASE_URL_CONFIG_KEY = "database.url";
42
478
  var CORE_CONFIG_TOKEN = "core.config";
@@ -46,6 +482,11 @@ var CORE_POLICY_GATE_TOKEN = "core.policyGate";
46
482
  var CORE_AUTH_TOKEN = "core.auth";
47
483
  var CORE_TOKEN_SERVICE_TOKEN = "core.tokenService";
48
484
  var DEFAULT_APP_PORT = 3000;
485
+ var DEFAULT_CACHE_TTL_MS = 3600000;
486
+ var DEFAULT_CACHE_MAX_ENTRIES = 100;
487
+ var DEFAULT_CACHE_DRIVER = "array";
488
+ var DEFAULT_API_TOKEN = "";
489
+ var DEFAULT_QUEUE_DRIVER = "sync";
49
490
 
50
491
  // ../../src/bootstrap/contracts.ts
51
492
  class ServiceContainer {
@@ -142,22 +583,3589 @@ function requireActiveApplicationContext() {
142
583
  }
143
584
  return activeContext;
144
585
  }
586
+ function resolveApplicationCache() {
587
+ return getRequiredDependency(requireActiveApplicationContext().dependencies, "cache");
588
+ }
145
589
  function resolveApplicationQueue() {
146
590
  return requireActiveApplicationContext().container.resolve(CORE_QUEUE_TOKEN);
147
591
  }
148
- // ../../src/config/frontend.ts
149
- function readFrontendMode() {
150
- const mode = (process.env.FRONTEND_MODE ?? "api").trim();
151
- if (mode === "server-htmx") {
152
- return "server-htmx";
592
+ // ../../src/bootstrap/discoverModules.ts
593
+ import { readdirSync } from "fs";
594
+ import { join } from "path";
595
+ import { pathToFileURL } from "url";
596
+ async function loadDiscoveredModules() {
597
+ const modulesDirectory = join(import.meta.dir, "../modules");
598
+ const moduleNames = readdirSync(modulesDirectory, { withFileTypes: true }).filter((entry) => entry.isDirectory()).map((entry) => entry.name);
599
+ const modules = await Promise.all(moduleNames.map(async (moduleName) => {
600
+ const moduleUrl = pathToFileURL(join(modulesDirectory, moduleName, "index.ts")).href;
601
+ const loaded = await import(moduleUrl);
602
+ return loaded.default;
603
+ }));
604
+ return modules.filter((module) => module?.name !== undefined).sort((left, right) => (left.order ?? 100) - (right.order ?? 100));
605
+ }
606
+ var appModules = await loadDiscoveredModules();
607
+ // ../../src/config/auth.ts
608
+ var authConfig = {
609
+ allowDevHeaders: (process.env.AUTH_DEV_HEADERS ?? "true") !== "false",
610
+ tokenDefaultAbilities: ["*"]
611
+ };
612
+
613
+ // ../../src/domain/abilities.ts
614
+ var MEMBER_ABILITIES = [
615
+ "organizations:read",
616
+ "projects:read",
617
+ "projects:create",
618
+ "tasks:read",
619
+ "tasks:create",
620
+ "comments:read",
621
+ "comments:create",
622
+ "attachments:read",
623
+ "attachments:create",
624
+ "auth:tokens:read",
625
+ "auth:tokens:write"
626
+ ];
627
+ var ADMIN_ABILITIES = [
628
+ ...MEMBER_ABILITIES,
629
+ "organizations:create",
630
+ "organizations:update",
631
+ "organizations:delete",
632
+ "projects:update",
633
+ "projects:delete",
634
+ "tasks:update",
635
+ "tasks:delete",
636
+ "comments:update",
637
+ "comments:delete",
638
+ "attachments:delete",
639
+ "webhooks:read",
640
+ "webhooks:write",
641
+ "audit:read"
642
+ ];
643
+ var PLATFORM_ADMIN_ABILITIES = ["*"];
644
+ function resolveAbilitiesForRole(role) {
645
+ if (role === "admin") {
646
+ return [...PLATFORM_ADMIN_ABILITIES];
647
+ }
648
+ return [...MEMBER_ABILITIES];
649
+ }
650
+
651
+ // ../../src/modules/user/provider.ts
652
+ import { OidcProvider } from "@getstrata/core/auth/oauth/oidcProvider";
653
+ import { GitHubOAuthProvider, MockOAuthProvider } from "@getstrata/core/auth/oauth/providers";
654
+ import { SamlProvider } from "@getstrata/core/auth/oauth/samlProvider";
655
+
656
+ // ../../src/modules/user/apiTokenRepository.ts
657
+ import { BaseRepository } from "@getstrata/core/database";
658
+
659
+ // ../../src/modules/user/apiTokenTable.ts
660
+ import { defineTable } from "@getstrata/core/database";
661
+ var apiTokenTable = defineTable({
662
+ name: "api_token",
663
+ primaryKey: "id",
664
+ columns: [
665
+ "id",
666
+ "user_id",
667
+ "name",
668
+ "token_hash",
669
+ "abilities",
670
+ "last_used_at",
671
+ "expires_at",
672
+ "created_at"
673
+ ],
674
+ defaultOrderBy: { column: "id", direction: "ASC" }
675
+ });
676
+
677
+ // ../../src/modules/user/authService.ts
678
+ import { verifyPassword } from "@getstrata/core/auth/password";
679
+ import { revealMfaSecret } from "@getstrata/core/crypto/mfaSecret";
680
+ import { UnauthorizedError as UnauthorizedError2 } from "@getstrata/core/errors/http";
681
+ import { logSecurityEvent } from "@getstrata/core/security/securityEvents";
682
+ import { resolveDefaultTokenExpiryDays } from "@getstrata/core/security/tokenExpiry";
683
+ import { verifyTotp } from "@getstrata/core/security/totp";
684
+ import { currentTenantId } from "@getstrata/core/tenant/tenantContext";
685
+ class AuthService {
686
+ users;
687
+ tokens;
688
+ oauthIdentities;
689
+ oauthProviders = new Map;
690
+ constructor(users, tokens, oauthIdentities) {
691
+ this.users = users;
692
+ this.tokens = tokens;
693
+ this.oauthIdentities = oauthIdentities;
694
+ }
695
+ registerOAuthProvider(provider) {
696
+ this.oauthProviders.set(provider.name, provider);
697
+ }
698
+ getOAuthProvider(name) {
699
+ return this.oauthProviders.get(name);
700
+ }
701
+ async loginWithPassword(email, password, options = {}) {
702
+ const user = await this.users.findByEmail(email);
703
+ if (!user?.password_hash) {
704
+ logSecurityEvent("auth_login_failed", { reason: "unknown_user", email });
705
+ throw new UnauthorizedError2("Invalid credentials.");
706
+ }
707
+ const valid = await verifyPassword(password, user.password_hash);
708
+ if (!valid) {
709
+ logSecurityEvent("auth_login_failed", { reason: "invalid_password", user_id: user.id });
710
+ throw new UnauthorizedError2("Invalid credentials.");
711
+ }
712
+ if (isFeatureEnabled("emailVerification") && !user.email_verified_at) {
713
+ logSecurityEvent("auth_login_blocked", { reason: "email_unverified", user_id: user.id });
714
+ throw new UnauthorizedError2("Email address is not verified.");
715
+ }
716
+ if (isFeatureEnabled("mfa") && user.mfa_enabled) {
717
+ const mfaSecret = revealMfaSecret(user.mfa_secret);
718
+ if (!mfaSecret || !options.mfaCode || !verifyTotp(mfaSecret, options.mfaCode)) {
719
+ logSecurityEvent("auth_login_failed", { reason: "invalid_mfa", user_id: user.id });
720
+ throw new UnauthorizedError2("Invalid MFA code.");
721
+ }
722
+ }
723
+ logSecurityEvent("auth_login_success", { user_id: user.id, method: "password" });
724
+ return await this.tokens.createToken(user.id, {
725
+ name: "password-login",
726
+ abilities: resolveAbilitiesForRole(user.role),
727
+ expiresInDays: resolveDefaultTokenExpiryDays() ?? undefined
728
+ });
729
+ }
730
+ async loginWithOAuth(providerName, code) {
731
+ const provider = this.oauthProviders.get(providerName);
732
+ if (!provider) {
733
+ throw new UnauthorizedError2("Unsupported OAuth provider.");
734
+ }
735
+ const profile = await provider.exchangeCode(code);
736
+ const user = await this.findOrCreateOAuthUser(providerName, profile);
737
+ logSecurityEvent("auth_login_success", { user_id: user.id, method: `oauth:${providerName}` });
738
+ return await this.tokens.createToken(user.id, {
739
+ name: `${providerName}-oauth`,
740
+ abilities: resolveAbilitiesForRole(user.role),
741
+ expiresInDays: resolveDefaultTokenExpiryDays() ?? undefined
742
+ });
743
+ }
744
+ buildOAuthAuthorizationUrl(providerName, state) {
745
+ const provider = this.oauthProviders.get(providerName);
746
+ if (!provider) {
747
+ throw new UnauthorizedError2("Unsupported OAuth provider.");
748
+ }
749
+ return provider.getAuthorizationUrl(state);
750
+ }
751
+ async findOrCreateOAuthUser(providerName, profile) {
752
+ const existingIdentity = await this.oauthIdentities.findByProviderUser(providerName, profile.providerUserId);
753
+ if (existingIdentity) {
754
+ return await this.users.findByIdOrThrow(existingIdentity.user_id);
755
+ }
756
+ const existingUser = await this.users.findByEmail(profile.email);
757
+ const user = existingUser ?? await this.users.create({
758
+ name: profile.name,
759
+ email: profile.email,
760
+ role: "member",
761
+ tenant_id: currentTenantId(),
762
+ email_verified_at: new Date,
763
+ created_at: new Date,
764
+ updated_at: new Date
765
+ });
766
+ await this.oauthIdentities.create({
767
+ user_id: user.id,
768
+ provider: providerName,
769
+ provider_user_id: profile.providerUserId,
770
+ email: profile.email,
771
+ created_at: new Date
772
+ });
773
+ return user;
774
+ }
775
+ }
776
+
777
+ // ../../src/modules/user/notificationRepository.ts
778
+ import { BaseRepository as BaseRepository2 } from "@getstrata/core/database";
779
+
780
+ // ../../src/modules/user/notificationTable.ts
781
+ import { defineTable as defineTable2 } from "@getstrata/core/database";
782
+ var notificationTable = defineTable2({
783
+ name: "notification",
784
+ primaryKey: "id",
785
+ columns: ["id", "user_id", "tenant_id", "type", "title", "body", "data", "read_at", "created_at"],
786
+ defaultOrderBy: { column: "created_at", direction: "DESC" }
787
+ });
788
+
789
+ // ../../src/modules/user/notificationService.ts
790
+ import { NotFoundError } from "@getstrata/core/errors/http";
791
+
792
+ // ../../src/modules/user/oauthIdentityRepository.ts
793
+ import { BaseRepository as BaseRepository3, defineTable as defineTable3 } from "@getstrata/core/database";
794
+ var oauthIdentityTable = defineTable3({
795
+ name: "oauth_identity",
796
+ primaryKey: "id",
797
+ columns: ["id", "user_id", "provider", "provider_user_id", "email", "created_at"]
798
+ });
799
+
800
+ // ../../src/modules/user/repository.ts
801
+ import {
802
+ emailLookupForQuery,
803
+ protectEmail,
804
+ revealEmail
805
+ } from "@getstrata/core/crypto/fieldEncryption";
806
+ import { revealMfaSecret as revealMfaSecret2 } from "@getstrata/core/crypto/mfaSecret";
807
+ import { BaseRepository as BaseRepository4 } from "@getstrata/core/database";
808
+ import { currentTenantId as currentTenantId2 } from "@getstrata/core/tenant/tenantContext";
809
+
810
+ // ../../src/modules/user/table.ts
811
+ import { defineTable as defineTable4 } from "@getstrata/core/database";
812
+ var userTable = defineTable4({
813
+ name: "users",
814
+ primaryKey: "id",
815
+ columns: [
816
+ "id",
817
+ "name",
818
+ "email",
819
+ "email_lookup",
820
+ "role",
821
+ "tenant_id",
822
+ "password_hash",
823
+ "email_verified_at",
824
+ "mfa_secret",
825
+ "mfa_enabled",
826
+ "created_at",
827
+ "updated_at"
828
+ ],
829
+ defaultOrderBy: { column: "id", direction: "ASC" }
830
+ });
831
+
832
+ // ../../src/modules/user/tokenService.ts
833
+ import { hashApiToken } from "@getstrata/core/auth/tokenHash";
834
+ import { ForbiddenError as ForbiddenError2, NotFoundError as NotFoundError2 } from "@getstrata/core/errors/http";
835
+ import { resolveDefaultTokenExpiryDays as resolveDefaultTokenExpiryDays2 } from "@getstrata/core/security/tokenExpiry";
836
+
837
+ // ../../src/modules/user/provider.ts
838
+ var tokenServiceToken = CORE_TOKEN_SERVICE_TOKEN;
839
+
840
+ // ../../src/core/auth/authContext.ts
841
+ import { AsyncLocalStorage as AsyncLocalStorage2 } from "async_hooks";
842
+ var authContext = new AsyncLocalStorage2;
843
+ function runWithAuthUser(user, callback) {
844
+ return authContext.run(user, callback);
845
+ }
846
+ function currentAuthUser() {
847
+ return authContext.getStore() ?? null;
848
+ }
849
+
850
+ // ../../src/core/auth/guard.ts
851
+ function devHeaderAbilities(role) {
852
+ if (role === "admin") {
853
+ return [...ADMIN_ABILITIES];
854
+ }
855
+ return [...MEMBER_ABILITIES];
856
+ }
857
+
858
+ class GuestGuard {
859
+ resolve(request) {
860
+ const userId = request.headers.get("x-authenticated-user-id");
861
+ if (!userId) {
862
+ return null;
863
+ }
864
+ const role = request.headers.get("x-authenticated-user-role");
865
+ return {
866
+ id: userId,
867
+ abilities: devHeaderAbilities(role),
868
+ ...role ? { role } : {}
869
+ };
870
+ }
871
+ }
872
+ class DatabaseTokenGuard {
873
+ container;
874
+ constructor(container) {
875
+ this.container = container;
876
+ }
877
+ async resolve(request) {
878
+ const authorization = request.headers.get("authorization");
879
+ if (!authorization?.startsWith("Bearer ")) {
880
+ return null;
881
+ }
882
+ const token = authorization.slice("Bearer ".length).trim();
883
+ if (!token) {
884
+ return null;
885
+ }
886
+ if (!this.container.has(tokenServiceToken)) {
887
+ return null;
888
+ }
889
+ const tokenService = this.container.resolve(tokenServiceToken);
890
+ return await tokenService.resolveUserFromToken(token);
891
+ }
892
+ }
893
+
894
+ class CompositeGuard {
895
+ guards;
896
+ constructor(guards) {
897
+ this.guards = guards;
898
+ }
899
+ async resolve(request) {
900
+ for (const guard of this.guards) {
901
+ const user = await Promise.resolve(guard.resolve(request));
902
+ if (user) {
903
+ return user;
904
+ }
905
+ }
906
+ return null;
907
+ }
908
+ }
909
+
910
+ class AuthManager {
911
+ guard;
912
+ constructor(guard) {
913
+ this.guard = guard;
914
+ }
915
+ async resolve(request) {
916
+ if (request) {
917
+ return await Promise.resolve(this.guard.resolve(request));
918
+ }
919
+ return currentAuthUser();
920
+ }
921
+ user(request) {
922
+ return this.resolve(request);
923
+ }
924
+ async check(request) {
925
+ return await this.user(request) !== null;
926
+ }
927
+ async requireUser(request) {
928
+ const user = await this.user(request);
929
+ if (!user) {
930
+ throw new UnauthorizedError;
931
+ }
932
+ return user;
933
+ }
934
+ }
935
+
936
+ // ../../src/core/auth/sessionCookie.ts
937
+ import { createHmac, timingSafeEqual } from "crypto";
938
+ var SESSION_COOKIE = "workhub_session";
939
+ var SESSION_TTL_SECONDS = 60 * 60 * 24 * 7;
940
+ function resolveSessionSecret() {
941
+ return process.env.SESSION_SECRET?.trim() || process.env.OAUTH_STATE_SECRET?.trim() || process.env.ADMIN_API_TOKEN?.trim() || "workhub-dev-session-secret";
942
+ }
943
+ function signSession(userId, issuedAt) {
944
+ const payload = `${userId}.${issuedAt}`;
945
+ const signature = createHmac("sha256", resolveSessionSecret()).update(payload).digest("hex");
946
+ return `${payload}.${signature}`;
947
+ }
948
+ function readCookieValue(request, cookieName) {
949
+ const cookieHeader = request.headers.get("cookie");
950
+ if (!cookieHeader) {
951
+ return null;
952
+ }
953
+ for (const part of cookieHeader.split(";")) {
954
+ const [name, ...rest] = part.trim().split("=");
955
+ if (name === cookieName) {
956
+ return decodeURIComponent(rest.join("="));
957
+ }
958
+ }
959
+ return null;
960
+ }
961
+ function readSessionUserId(request) {
962
+ const cookieValue = readCookieValue(request, SESSION_COOKIE);
963
+ if (!cookieValue) {
964
+ return null;
965
+ }
966
+ const parts = cookieValue.split(".");
967
+ if (parts.length !== 3) {
968
+ return null;
969
+ }
970
+ const [userIdRaw, issuedAtRaw, cookieSignature] = parts;
971
+ const userId = Number.parseInt(String(userIdRaw), 10);
972
+ const issuedAt = Number.parseInt(String(issuedAtRaw), 10);
973
+ if (!Number.isInteger(userId) || userId <= 0 || !Number.isFinite(issuedAt)) {
974
+ return null;
975
+ }
976
+ if (Date.now() - issuedAt > SESSION_TTL_SECONDS * 1000) {
977
+ return null;
978
+ }
979
+ const expectedSignature = signSession(userId, issuedAt).split(".").pop();
980
+ if (!expectedSignature || !cookieSignature) {
981
+ return null;
982
+ }
983
+ const expectedBuffer = Buffer.from(expectedSignature);
984
+ const actualBuffer = Buffer.from(cookieSignature);
985
+ if (expectedBuffer.length !== actualBuffer.length) {
986
+ return null;
987
+ }
988
+ if (!timingSafeEqual(expectedBuffer, actualBuffer)) {
989
+ return null;
990
+ }
991
+ return userId;
992
+ }
993
+
994
+ // ../../src/core/auth/sessionGuard.ts
995
+ class SessionGuard {
996
+ container;
997
+ constructor(container) {
998
+ this.container = container;
999
+ }
1000
+ async resolve(request) {
1001
+ const userId = readSessionUserId(request);
1002
+ if (!userId) {
1003
+ return null;
1004
+ }
1005
+ if (!this.container.has(tokenServiceToken)) {
1006
+ return null;
1007
+ }
1008
+ const tokenService = this.container.resolve(tokenServiceToken);
1009
+ try {
1010
+ const user = await tokenService.findByIdOrThrow(userId);
1011
+ return {
1012
+ id: user.id,
1013
+ role: user.role,
1014
+ abilities: resolveAbilitiesForRole(user.role)
1015
+ };
1016
+ } catch {
1017
+ return null;
1018
+ }
1019
+ }
1020
+ }
1021
+
1022
+ // ../../src/bootstrap/providers/auth.ts
1023
+ var authProvider = {
1024
+ name: "core.auth",
1025
+ register({ container, config }) {
1026
+ config.set("auth.allowDevHeaders", authConfig.allowDevHeaders);
1027
+ const guards = [new DatabaseTokenGuard(container), new SessionGuard(container)];
1028
+ if (authConfig.allowDevHeaders) {
1029
+ guards.push(new GuestGuard);
1030
+ }
1031
+ container.set(CORE_AUTH_TOKEN, new AuthManager(new CompositeGuard(guards)));
1032
+ }
1033
+ };
1034
+ var auth_default = authProvider;
1035
+
1036
+ // ../../src/core/cache/redisCacheStore.ts
1037
+ var {RedisClient } = globalThis.Bun;
1038
+ var KEY_PREFIX = "workhub:cache:";
1039
+ var TAG_PREFIX = "workhub:cache:tag:";
1040
+
1041
+ class RedisCacheStore {
1042
+ ttlMs;
1043
+ maxEntries;
1044
+ client;
1045
+ inflight = new Map;
1046
+ keyTags = new Map;
1047
+ constructor(redisUrl, ttlMs, maxEntries) {
1048
+ this.ttlMs = ttlMs;
1049
+ this.maxEntries = maxEntries;
1050
+ this.client = new RedisClient(redisUrl);
1051
+ }
1052
+ async get(key) {
1053
+ const raw = await this.client.get(this.storageKey(key));
1054
+ if (raw === null) {
1055
+ return;
1056
+ }
1057
+ return JSON.parse(raw);
1058
+ }
1059
+ async set(key, value, ttlMs) {
1060
+ const resolvedTtlMs = ttlMs ?? this.ttlMs;
1061
+ const payload = JSON.stringify(value);
1062
+ if (resolvedTtlMs > 0) {
1063
+ await this.client.psetex(this.storageKey(key), resolvedTtlMs, payload);
1064
+ } else {
1065
+ await this.client.set(this.storageKey(key), payload);
1066
+ }
1067
+ await this.enforceMaxEntries();
1068
+ }
1069
+ async getOrSet(key, loader, ttlMs) {
1070
+ const cached = await this.get(key);
1071
+ if (cached !== undefined) {
1072
+ return cached;
1073
+ }
1074
+ const inflightRequest = this.inflight.get(key);
1075
+ if (inflightRequest) {
1076
+ return inflightRequest;
1077
+ }
1078
+ const pendingRequest = loader().then(async (value) => {
1079
+ await this.set(key, value, ttlMs);
1080
+ return value;
1081
+ }).finally(() => {
1082
+ this.inflight.delete(key);
1083
+ });
1084
+ this.inflight.set(key, pendingRequest);
1085
+ return pendingRequest;
1086
+ }
1087
+ async attachTags(key, tags) {
1088
+ if (tags.length === 0) {
1089
+ return;
1090
+ }
1091
+ let tagsForKey = this.keyTags.get(key);
1092
+ if (!tagsForKey) {
1093
+ tagsForKey = new Set;
1094
+ this.keyTags.set(key, tagsForKey);
1095
+ }
1096
+ for (const tag of tags) {
1097
+ tagsForKey.add(tag);
1098
+ await this.client.sadd(this.tagKey(tag), key);
1099
+ }
1100
+ }
1101
+ async flushTags(tags) {
1102
+ const keysToRemove = new Set;
1103
+ for (const tag of tags) {
1104
+ const members = await this.client.smembers(this.tagKey(tag));
1105
+ for (const member of members) {
1106
+ keysToRemove.add(member);
1107
+ }
1108
+ }
1109
+ let removed = 0;
1110
+ for (const key of keysToRemove) {
1111
+ if (await this.invalidate(key)) {
1112
+ removed += 1;
1113
+ }
1114
+ }
1115
+ for (const tag of tags) {
1116
+ await this.client.del(this.tagKey(tag));
1117
+ }
1118
+ return removed;
1119
+ }
1120
+ async invalidate(key) {
1121
+ const deleted = await this.client.del(this.storageKey(key));
1122
+ await this.detachKeyFromTags(key);
1123
+ return deleted > 0;
1124
+ }
1125
+ async invalidateByPrefix(prefix) {
1126
+ const keys = await this.client.keys(`${KEY_PREFIX}*`);
1127
+ let removed = 0;
1128
+ for (const storageKey of keys) {
1129
+ const key = storageKey.slice(KEY_PREFIX.length);
1130
+ if (key === prefix || key.startsWith(`${prefix}?`)) {
1131
+ if (await this.invalidate(key)) {
1132
+ removed += 1;
1133
+ }
1134
+ }
1135
+ }
1136
+ return removed;
1137
+ }
1138
+ async clear() {
1139
+ const keys = await this.client.keys(`${KEY_PREFIX}*`);
1140
+ if (keys.length > 0) {
1141
+ await this.client.del(...keys);
1142
+ }
1143
+ const tagKeys = await this.client.keys(`${TAG_PREFIX}*`);
1144
+ if (tagKeys.length > 0) {
1145
+ await this.client.del(...tagKeys);
1146
+ }
1147
+ this.inflight.clear();
1148
+ this.keyTags.clear();
1149
+ }
1150
+ async size() {
1151
+ const keys = await this.client.keys(`${KEY_PREFIX}*`);
1152
+ return keys.length;
1153
+ }
1154
+ storageKey(key) {
1155
+ return `${KEY_PREFIX}${key}`;
1156
+ }
1157
+ tagKey(tag) {
1158
+ return `${TAG_PREFIX}${tag}`;
1159
+ }
1160
+ async detachKeyFromTags(key) {
1161
+ const tags = this.keyTags.get(key);
1162
+ if (!tags) {
1163
+ return;
1164
+ }
1165
+ for (const tag of tags) {
1166
+ await this.client.srem(this.tagKey(tag), key);
1167
+ }
1168
+ this.keyTags.delete(key);
1169
+ }
1170
+ async enforceMaxEntries() {
1171
+ const keys = await this.client.keys(`${KEY_PREFIX}*`);
1172
+ if (keys.length <= this.maxEntries) {
1173
+ return;
1174
+ }
1175
+ const overflow = keys.length - this.maxEntries;
1176
+ const keysToRemove = keys.slice(0, overflow);
1177
+ if (keysToRemove.length > 0) {
1178
+ await this.client.del(...keysToRemove);
1179
+ }
1180
+ }
1181
+ }
1182
+ var redisCacheStore_default = RedisCacheStore;
1183
+
1184
+ // ../../src/core/cache/simpleCache.ts
1185
+ class SimpleCache {
1186
+ ttlMs;
1187
+ maxEntries;
1188
+ cache = new Map;
1189
+ inflight = new Map;
1190
+ tagIndex = new Map;
1191
+ keyTags = new Map;
1192
+ constructor(ttlMs = 3600000, maxEntries = 100) {
1193
+ this.ttlMs = ttlMs;
1194
+ this.maxEntries = maxEntries;
1195
+ if (!Number.isFinite(ttlMs) || ttlMs < 0) {
1196
+ throw new RangeError("ttlMs must be a non-negative number.");
1197
+ }
1198
+ if (!Number.isInteger(maxEntries) || maxEntries < 1) {
1199
+ throw new RangeError("maxEntries must be a positive integer.");
1200
+ }
1201
+ }
1202
+ get(key) {
1203
+ return this.getFreshEntry(key)?.value;
1204
+ }
1205
+ set(key, value, ttlMs) {
1206
+ const now = Date.now();
1207
+ const resolvedTtlMs = ttlMs ?? this.ttlMs;
1208
+ this.cache.set(key, {
1209
+ value,
1210
+ expiresAt: now + resolvedTtlMs,
1211
+ lastAccessedAt: now
1212
+ });
1213
+ this.evictOverflow();
1214
+ }
1215
+ async getOrSet(key, loader, ttlMs) {
1216
+ this.pruneExpired();
1217
+ const cachedEntry = this.getFreshEntry(key);
1218
+ if (cachedEntry) {
1219
+ return cachedEntry.value;
1220
+ }
1221
+ const inflightRequest = this.inflight.get(key);
1222
+ if (inflightRequest) {
1223
+ return inflightRequest;
1224
+ }
1225
+ const pendingRequest = loader().then((value) => {
1226
+ this.set(key, value, ttlMs);
1227
+ return value;
1228
+ }).finally(() => {
1229
+ this.inflight.delete(key);
1230
+ });
1231
+ this.inflight.set(key, pendingRequest);
1232
+ return pendingRequest;
1233
+ }
1234
+ attachTags(key, tags) {
1235
+ if (tags.length === 0) {
1236
+ return;
1237
+ }
1238
+ let tagsForKey = this.keyTags.get(key);
1239
+ if (!tagsForKey) {
1240
+ tagsForKey = new Set;
1241
+ this.keyTags.set(key, tagsForKey);
1242
+ }
1243
+ for (const tag of tags) {
1244
+ tagsForKey.add(tag);
1245
+ let keysForTag = this.tagIndex.get(tag);
1246
+ if (!keysForTag) {
1247
+ keysForTag = new Set;
1248
+ this.tagIndex.set(tag, keysForTag);
1249
+ }
1250
+ keysForTag.add(key);
1251
+ }
1252
+ }
1253
+ flushTags(tags) {
1254
+ const keysToRemove = new Set;
1255
+ for (const tag of tags) {
1256
+ const keys = this.tagIndex.get(tag);
1257
+ if (!keys) {
1258
+ continue;
1259
+ }
1260
+ for (const key of keys) {
1261
+ keysToRemove.add(key);
1262
+ }
1263
+ }
1264
+ let removed = 0;
1265
+ for (const key of keysToRemove) {
1266
+ if (this.invalidate(key)) {
1267
+ removed += 1;
1268
+ }
1269
+ }
1270
+ for (const tag of tags) {
1271
+ this.tagIndex.delete(tag);
1272
+ }
1273
+ return removed;
1274
+ }
1275
+ invalidate(key) {
1276
+ const removed = this.cache.delete(key);
1277
+ if (removed) {
1278
+ this.detachKeyFromTags(key);
1279
+ }
1280
+ return removed;
1281
+ }
1282
+ invalidateByPrefix(prefix) {
1283
+ let removed = 0;
1284
+ for (const key of [...this.cache.keys()]) {
1285
+ if (key === prefix || key.startsWith(`${prefix}?`)) {
1286
+ if (this.invalidate(key)) {
1287
+ removed += 1;
1288
+ }
1289
+ }
1290
+ }
1291
+ return removed;
1292
+ }
1293
+ clear() {
1294
+ this.cache.clear();
1295
+ this.inflight.clear();
1296
+ this.tagIndex.clear();
1297
+ this.keyTags.clear();
1298
+ }
1299
+ size() {
1300
+ this.pruneExpired();
1301
+ return this.cache.size;
1302
+ }
1303
+ detachKeyFromTags(key) {
1304
+ const tags = this.keyTags.get(key);
1305
+ if (!tags) {
1306
+ return;
1307
+ }
1308
+ for (const tag of tags) {
1309
+ const keys = this.tagIndex.get(tag);
1310
+ if (!keys) {
1311
+ continue;
1312
+ }
1313
+ keys.delete(key);
1314
+ if (keys.size === 0) {
1315
+ this.tagIndex.delete(tag);
1316
+ }
1317
+ }
1318
+ this.keyTags.delete(key);
1319
+ }
1320
+ getFreshEntry(key) {
1321
+ const entry = this.cache.get(key);
1322
+ if (!entry) {
1323
+ return;
1324
+ }
1325
+ if (entry.expiresAt <= Date.now()) {
1326
+ this.invalidate(key);
1327
+ return;
1328
+ }
1329
+ entry.lastAccessedAt = Date.now();
1330
+ return entry;
1331
+ }
1332
+ pruneExpired() {
1333
+ const now = Date.now();
1334
+ for (const [key, entry] of this.cache.entries()) {
1335
+ if (entry.expiresAt <= now) {
1336
+ this.invalidate(key);
1337
+ }
1338
+ }
1339
+ }
1340
+ evictOverflow() {
1341
+ while (this.cache.size > this.maxEntries) {
1342
+ let oldestKey;
1343
+ let oldestAccessTime = Number.POSITIVE_INFINITY;
1344
+ for (const [key, entry] of this.cache.entries()) {
1345
+ if (entry.lastAccessedAt < oldestAccessTime) {
1346
+ oldestAccessTime = entry.lastAccessedAt;
1347
+ oldestKey = key;
1348
+ }
1349
+ }
1350
+ if (!oldestKey) {
1351
+ return;
1352
+ }
1353
+ this.invalidate(oldestKey);
1354
+ }
1355
+ }
1356
+ }
1357
+ var simpleCache_default = SimpleCache;
1358
+
1359
+ // ../../src/core/cache/simpleCacheStore.ts
1360
+ class SimpleCacheStore {
1361
+ cache;
1362
+ constructor(cache) {
1363
+ this.cache = cache;
1364
+ }
1365
+ get(key) {
1366
+ return Promise.resolve(this.cache.get(key));
1367
+ }
1368
+ set(key, value, ttlMs) {
1369
+ this.cache.set(key, value, ttlMs);
1370
+ return Promise.resolve();
1371
+ }
1372
+ getOrSet(key, loader, ttlMs) {
1373
+ return this.cache.getOrSet(key, loader, ttlMs);
1374
+ }
1375
+ attachTags(key, tags) {
1376
+ this.cache.attachTags(key, tags);
1377
+ return Promise.resolve();
1378
+ }
1379
+ flushTags(tags) {
1380
+ return Promise.resolve(this.cache.flushTags(tags));
1381
+ }
1382
+ invalidate(key) {
1383
+ return Promise.resolve(this.cache.invalidate(key));
1384
+ }
1385
+ invalidateByPrefix(prefix) {
1386
+ return Promise.resolve(this.cache.invalidateByPrefix(prefix));
1387
+ }
1388
+ clear() {
1389
+ this.cache.clear();
1390
+ return Promise.resolve();
1391
+ }
1392
+ size() {
1393
+ return Promise.resolve(this.cache.size());
1394
+ }
1395
+ }
1396
+ var simpleCacheStore_default = SimpleCacheStore;
1397
+
1398
+ // ../../src/core/cache/createCacheStore.ts
1399
+ function createCacheStore(options) {
1400
+ if (options.driver === "redis") {
1401
+ if (!options.redisUrl) {
1402
+ throw new Error('CACHE_DRIVER="redis" requires REDIS_URL to be set.');
1403
+ }
1404
+ return new redisCacheStore_default(options.redisUrl, options.ttlMs, options.maxEntries);
1405
+ }
1406
+ return new simpleCacheStore_default(new simpleCache_default(options.ttlMs, options.maxEntries));
1407
+ }
1408
+
1409
+ // ../../src/core/cache/taggedCache.ts
1410
+ class TaggedCache {
1411
+ store;
1412
+ tags;
1413
+ constructor(store, tags) {
1414
+ this.store = store;
1415
+ this.tags = tags;
1416
+ }
1417
+ async remember(key, callback, ttlMs) {
1418
+ const value = await this.store.getOrSet(key, callback, ttlMs);
1419
+ await this.store.attachTags(key, this.tags);
1420
+ return value;
1421
+ }
1422
+ async flush() {
1423
+ return this.store.flushTags(this.tags);
1424
+ }
1425
+ }
1426
+ var taggedCache_default = TaggedCache;
1427
+
1428
+ // ../../src/core/cache/repository.ts
1429
+ class CacheRepository {
1430
+ store;
1431
+ constructor(store) {
1432
+ this.store = store;
1433
+ }
1434
+ async get(key) {
1435
+ return this.store.get(key);
1436
+ }
1437
+ async remember(key, callback, ttlMs) {
1438
+ return this.store.getOrSet(key, callback, ttlMs);
1439
+ }
1440
+ async forget(key) {
1441
+ return this.store.invalidate(key);
1442
+ }
1443
+ async flush() {
1444
+ await this.store.clear();
1445
+ }
1446
+ tags(...names) {
1447
+ return new taggedCache_default(this.store, names);
1448
+ }
1449
+ async getOrSet(key, loader, ttlMs) {
1450
+ return this.remember(key, loader, ttlMs);
1451
+ }
1452
+ async invalidate(key) {
1453
+ return this.forget(key);
1454
+ }
1455
+ async invalidateByPrefix(prefix) {
1456
+ return this.store.invalidateByPrefix(prefix);
1457
+ }
1458
+ async clear() {
1459
+ await this.flush();
1460
+ }
1461
+ async size() {
1462
+ return this.store.size();
1463
+ }
1464
+ }
1465
+ var repository_default2 = CacheRepository;
1466
+
1467
+ // ../../src/bootstrap/providers/cache.ts
1468
+ var cacheProvider = {
1469
+ name: "core.cache",
1470
+ register({ container, config, dependencies }) {
1471
+ container.singleton(CORE_CACHE_TOKEN, () => {
1472
+ const store = createCacheStore({
1473
+ driver: config.require(CACHE_DRIVER_CONFIG_KEY),
1474
+ ttlMs: config.require(CACHE_TTL_MS_CONFIG_KEY),
1475
+ maxEntries: config.require(CACHE_MAX_ENTRIES_CONFIG_KEY),
1476
+ redisUrl: config.get(REDIS_URL_CONFIG_KEY) || undefined
1477
+ });
1478
+ return new repository_default2(store);
1479
+ });
1480
+ dependencies.cache = container.resolve(CORE_CACHE_TOKEN);
1481
+ }
1482
+ };
1483
+ var cache_default = cacheProvider;
1484
+
1485
+ // ../../src/config/queue.ts
1486
+ var queueConfig = {
1487
+ driver: process.env.QUEUE_DRIVER === "redis" || process.env.QUEUE_DRIVER === "async" || process.env.QUEUE_DRIVER === "sync" ? process.env.QUEUE_DRIVER : DEFAULT_QUEUE_DRIVER,
1488
+ maxAttempts: Number(process.env.QUEUE_MAX_ATTEMPTS ?? "3"),
1489
+ backoffMs: Number(process.env.QUEUE_BACKOFF_MS ?? "1000")
1490
+ };
1491
+
1492
+ // ../../src/core/config/envSchema.ts
1493
+ function defineEnvSchema(schema) {
1494
+ return schema;
1495
+ }
1496
+ function validateEnv(schema, env = process.env) {
1497
+ const resolved = {};
1498
+ for (const [name, rule] of Object.entries(schema)) {
1499
+ const rawValue = env[name];
1500
+ const value = rawValue === undefined || rawValue.trim() === "" ? rule.default : rawValue;
1501
+ if (value === undefined || value.trim() === "") {
1502
+ if (rule.required) {
1503
+ throw new Error(`Missing required environment variable "${name}".`);
1504
+ }
1505
+ continue;
1506
+ }
1507
+ if (rule.integer) {
1508
+ const parsed = Number.parseInt(value, 10);
1509
+ const minimum = rule.minimum ?? Number.NEGATIVE_INFINITY;
1510
+ if (!Number.isInteger(parsed) || parsed < minimum) {
1511
+ const comparison = minimum === Number.NEGATIVE_INFINITY ? "an integer" : `an integer >= ${minimum}`;
1512
+ throw new Error(`Environment variable "${name}" must be ${comparison}.`);
1513
+ }
1514
+ }
1515
+ if (rule.pattern && !rule.pattern.test(value)) {
1516
+ throw new Error(`Environment variable "${name}" has an invalid format.`);
1517
+ }
1518
+ resolved[name] = value;
1519
+ }
1520
+ return resolved;
1521
+ }
1522
+
1523
+ // ../../src/bootstrap/env.ts
1524
+ var appEnvSchema = defineEnvSchema({
1525
+ DATABASE_URL: { required: true, pattern: /^postgres(ql)?:\/\// },
1526
+ PORT: {
1527
+ integer: true,
1528
+ minimum: 1,
1529
+ default: String(DEFAULT_APP_PORT)
1530
+ },
1531
+ CACHE_TTL_MS: {
1532
+ integer: true,
1533
+ minimum: 0,
1534
+ default: String(DEFAULT_CACHE_TTL_MS)
1535
+ },
1536
+ CACHE_MAX_ENTRIES: {
1537
+ integer: true,
1538
+ minimum: 1,
1539
+ default: String(DEFAULT_CACHE_MAX_ENTRIES)
1540
+ },
1541
+ CACHE_DRIVER: {
1542
+ default: DEFAULT_CACHE_DRIVER,
1543
+ pattern: /^(array|redis)$/
1544
+ },
1545
+ REDIS_URL: {
1546
+ default: ""
1547
+ },
1548
+ QUEUE_DRIVER: {
1549
+ default: DEFAULT_QUEUE_DRIVER,
1550
+ pattern: /^(sync|async|redis)$/
1551
+ },
1552
+ AUTH_DEV_HEADERS: {
1553
+ default: "true",
1554
+ pattern: /^(true|false|0|1)$/
1555
+ },
1556
+ APP_ENV: {
1557
+ default: "local"
1558
+ },
1559
+ APP_DEBUG: {
1560
+ default: "true"
1561
+ },
1562
+ APP_URL: {
1563
+ default: "http://localhost:3000"
1564
+ },
1565
+ API_PREFIX: {
1566
+ default: "/api/v1"
1567
+ },
1568
+ CORS_ALLOWED_ORIGINS: {
1569
+ default: "*"
1570
+ },
1571
+ QUEUE_MAX_ATTEMPTS: {
1572
+ integer: true,
1573
+ minimum: 1,
1574
+ default: "3"
1575
+ },
1576
+ QUEUE_BACKOFF_MS: {
1577
+ integer: true,
1578
+ minimum: 0,
1579
+ default: "1000"
1580
+ },
1581
+ ADMIN_API_TOKEN: {
1582
+ default: DEFAULT_API_TOKEN
1583
+ },
1584
+ MEMBER_API_TOKEN: {
1585
+ default: ""
1586
+ },
1587
+ DB_POOL_MAX: {
1588
+ integer: true,
1589
+ minimum: 1,
1590
+ default: "10"
1591
+ },
1592
+ DB_POOL_IDLE_TIMEOUT: {
1593
+ integer: true,
1594
+ minimum: 0,
1595
+ default: "30"
1596
+ },
1597
+ DB_POOL_MAX_LIFETIME: {
1598
+ integer: true,
1599
+ minimum: 0,
1600
+ default: "3600"
1601
+ },
1602
+ DB_CONNECTION_TIMEOUT: {
1603
+ integer: true,
1604
+ minimum: 1,
1605
+ default: "10"
1606
+ }
1607
+ });
1608
+
1609
+ // ../../src/bootstrap/providers/config.ts
1610
+ function parseInteger(value, envName, minimum) {
1611
+ const parsed = Number.parseInt(value, 10);
1612
+ if (!Number.isInteger(parsed) || parsed < minimum) {
1613
+ const comparison = minimum === 0 ? "a non-negative" : `an integer >= ${minimum}`;
1614
+ throw new Error(`${envName} must be ${comparison} value.`);
1615
+ }
1616
+ return parsed;
1617
+ }
1618
+ var configProvider = {
1619
+ name: "core.config",
1620
+ register({ container, config }) {
1621
+ const env = validateEnv(appEnvSchema);
1622
+ container.set(CORE_CONFIG_TOKEN, config);
1623
+ config.set(DATABASE_URL_CONFIG_KEY, env.DATABASE_URL);
1624
+ config.set(APP_PORT_CONFIG_KEY, parseInteger(env.PORT ?? String(DEFAULT_APP_PORT), "PORT", 1));
1625
+ config.set(CACHE_TTL_MS_CONFIG_KEY, parseInteger(env.CACHE_TTL_MS ?? String(DEFAULT_CACHE_TTL_MS), "CACHE_TTL_MS", 0));
1626
+ config.set(CACHE_MAX_ENTRIES_CONFIG_KEY, parseInteger(env.CACHE_MAX_ENTRIES ?? String(DEFAULT_CACHE_MAX_ENTRIES), "CACHE_MAX_ENTRIES", 1));
1627
+ config.set(CACHE_DRIVER_CONFIG_KEY, env.CACHE_DRIVER ?? DEFAULT_CACHE_DRIVER);
1628
+ config.set(REDIS_URL_CONFIG_KEY, env.REDIS_URL ?? "");
1629
+ config.set("app.env", appConfig.env);
1630
+ config.set("app.debug", appConfig.debug);
1631
+ config.set("app.url", appConfig.url);
1632
+ config.set("app.apiPrefix", appConfig.apiPrefix);
1633
+ config.set("auth.allowDevHeaders", authConfig.allowDevHeaders);
1634
+ config.set("queue.driver", queueConfig.driver);
1635
+ config.set("queue.maxAttempts", queueConfig.maxAttempts);
1636
+ config.set("queue.backoffMs", queueConfig.backoffMs);
1637
+ }
1638
+ };
1639
+ var config_default = configProvider;
1640
+
1641
+ // ../../src/core/events/eventBus.ts
1642
+ class EventBus {
1643
+ constructor() {}
1644
+ listeners = new Map;
1645
+ listen(event, listener) {
1646
+ const handlers = this.listeners.get(event) ?? new Set;
1647
+ handlers.add(listener);
1648
+ this.listeners.set(event, handlers);
1649
+ return () => {
1650
+ handlers.delete(listener);
1651
+ if (handlers.size === 0) {
1652
+ this.listeners.delete(event);
1653
+ }
1654
+ };
1655
+ }
1656
+ async dispatch(event, payload) {
1657
+ const handlers = this.listeners.get(event);
1658
+ if (!handlers || handlers.size === 0) {
1659
+ return;
1660
+ }
1661
+ for (const handler of handlers) {
1662
+ await handler(payload);
1663
+ }
1664
+ }
1665
+ }
1666
+ var eventBus = new EventBus;
1667
+
1668
+ // ../../src/core/events/index.ts
1669
+ function modelEventName(tableName, action) {
1670
+ return `${tableName}.${action}`;
1671
+ }
1672
+
1673
+ // ../../src/bootstrap/providers/events.ts
1674
+ var CORE_EVENT_BUS_TOKEN = "core.eventBus";
1675
+ var eventsProvider = {
1676
+ name: "core.events",
1677
+ register({ container }) {
1678
+ container.set(CORE_EVENT_BUS_TOKEN, eventBus);
1679
+ }
1680
+ };
1681
+ var events_default = eventsProvider;
1682
+
1683
+ // ../../src/bootstrap/discoverListeners.ts
1684
+ import { readdirSync as readdirSync2 } from "fs";
1685
+ import { join as join2 } from "path";
1686
+ import { pathToFileURL as pathToFileURL2 } from "url";
1687
+ async function loadDiscoveredListeners() {
1688
+ const listenersDirectory = join2(import.meta.dir, "../listeners");
1689
+ let entries;
1690
+ try {
1691
+ entries = readdirSync2(listenersDirectory, { withFileTypes: true }).filter((entry) => entry.isFile() && entry.name.endsWith(".ts")).map((entry) => entry.name);
1692
+ } catch (error) {
1693
+ if (error instanceof Error && "code" in error && error.code === "ENOENT") {
1694
+ return [];
1695
+ }
1696
+ throw error;
1697
+ }
1698
+ const listeners = await Promise.all(entries.map(async (fileName) => {
1699
+ const moduleUrl = pathToFileURL2(join2(listenersDirectory, fileName)).href;
1700
+ const loaded = await import(moduleUrl);
1701
+ return loaded.default;
1702
+ }));
1703
+ return listeners.filter((listener) => typeof listener === "function");
1704
+ }
1705
+ var appListeners = await loadDiscoveredListeners();
1706
+ function discoverListeners() {
1707
+ return appListeners;
1708
+ }
1709
+
1710
+ // ../../src/core/cache/modelCacheTags.ts
1711
+ function cacheTagsForModelWrite(tableName, action) {
1712
+ const module = appModules.find((entry) => entry.tableName === tableName);
1713
+ const baseTags = module?.cacheTags ?? [`${tableName}s`];
1714
+ const isDelete = action === "deleted" || action === "force-deleted";
1715
+ const extraTags = isDelete ? module?.cacheDeleteExtraTags ?? [] : [];
1716
+ return [...new Set([...baseTags, ...extraTags])];
1717
+ }
1718
+ function discoverModelTableNames() {
1719
+ return appModules.map((module) => module.tableName).filter((tableName) => tableName !== undefined);
1720
+ }
1721
+
1722
+ // ../../src/core/queue/index.ts
1723
+ class Job {
1724
+ maxAttempts;
1725
+ backoffMs;
1726
+ priority;
1727
+ }
1728
+
1729
+ // ../../src/core/jobs/invalidateCacheTagsJob.ts
1730
+ class InvalidateCacheTagsJob extends Job {
1731
+ cache;
1732
+ constructor(cache) {
1733
+ super();
1734
+ this.cache = cache;
1735
+ }
1736
+ async handle(payload) {
1737
+ await this.cache.tags(...payload.tags).flush();
1738
+ }
1739
+ }
1740
+ var invalidateCacheTagsJob_default = InvalidateCacheTagsJob;
1741
+
1742
+ // ../../src/core/jobs/dispatchWebhookJob.ts
1743
+ import { createHmac as createHmac2 } from "crypto";
1744
+ class DispatchWebhookJob extends Job {
1745
+ constructor() {
1746
+ super();
1747
+ }
1748
+ maxAttempts = 3;
1749
+ backoffMs = 2000;
1750
+ async handle(payload) {
1751
+ const rows = await connection_default`
1752
+ SELECT id, url, secret
1753
+ FROM webhook
1754
+ WHERE id = ${payload.webhookId} AND active = TRUE
1755
+ LIMIT 1
1756
+ `;
1757
+ const webhook = rows[0];
1758
+ if (!webhook) {
1759
+ return;
1760
+ }
1761
+ const body = JSON.stringify({ event: payload.event, payload: payload.payload });
1762
+ const signature = createHmac2("sha256", webhook.secret).update(body).digest("hex");
1763
+ assertSafeOutboundUrl(webhook.url, { allowHttp: appConfig.env !== "production" });
1764
+ let responseStatus = null;
1765
+ let errorMessage = null;
1766
+ try {
1767
+ const response = await safeFetch(webhook.url, {
1768
+ method: "POST",
1769
+ headers: {
1770
+ "content-type": "application/json",
1771
+ "x-workhub-signature": signature
1772
+ },
1773
+ body
1774
+ });
1775
+ responseStatus = response.status;
1776
+ if (!response.ok) {
1777
+ throw new Error(`Webhook delivery failed with status ${response.status}.`);
1778
+ }
1779
+ } catch (error) {
1780
+ errorMessage = error instanceof Error ? error.message : String(error);
1781
+ await connection_default`
1782
+ INSERT INTO webhook_delivery (webhook_id, event, payload, response_status, error)
1783
+ VALUES (
1784
+ ${webhook.id},
1785
+ ${payload.event},
1786
+ ${JSON.stringify(payload.payload)}::jsonb,
1787
+ ${responseStatus},
1788
+ ${errorMessage}
1789
+ )
1790
+ `;
1791
+ throw error instanceof Error ? error : new Error(errorMessage);
1792
+ }
1793
+ await connection_default`
1794
+ INSERT INTO webhook_delivery (webhook_id, event, payload, response_status)
1795
+ VALUES (
1796
+ ${webhook.id},
1797
+ ${payload.event},
1798
+ ${JSON.stringify(payload.payload)}::jsonb,
1799
+ ${responseStatus}
1800
+ )
1801
+ `;
1802
+ }
1803
+ }
1804
+ var dispatchWebhookJob_default = DispatchWebhookJob;
1805
+
1806
+ // ../../src/core/queue/jobRegistry.ts
1807
+ class JobRegistry {
1808
+ constructor() {}
1809
+ factories = new Map;
1810
+ instances = new WeakMap;
1811
+ register(name, factory) {
1812
+ this.factories.set(name, factory);
1813
+ }
1814
+ resolveName(job) {
1815
+ return this.instances.get(job);
1816
+ }
1817
+ track(name, job) {
1818
+ this.instances.set(job, name);
1819
+ return job;
1820
+ }
1821
+ create(name) {
1822
+ const factory = this.factories.get(name);
1823
+ if (!factory) {
1824
+ return;
1825
+ }
1826
+ return factory();
1827
+ }
1828
+ names() {
1829
+ return [...this.factories.keys()];
1830
+ }
1831
+ }
1832
+ var jobRegistry = new JobRegistry;
1833
+
1834
+ // ../../src/core/pagination/index.ts
1835
+ function buildPaginationMeta(input) {
1836
+ const lastPage = Math.max(1, Math.ceil(input.total / input.perPage));
1837
+ return {
1838
+ page: input.page,
1839
+ per_page: input.perPage,
1840
+ total: input.total,
1841
+ last_page: lastPage
1842
+ };
1843
+ }
1844
+
1845
+ // ../../src/core/database/errors.ts
1846
+ function isPostgresError(error) {
1847
+ return typeof error === "object" && error !== null && (("errno" in error) || ("code" in error));
1848
+ }
1849
+ function getPostgresSqlState(error) {
1850
+ if (typeof error.errno === "string" && /^\d{5}$/.test(error.errno)) {
1851
+ return error.errno;
1852
+ }
1853
+ if (typeof error.errno === "number") {
1854
+ return String(error.errno).padStart(5, "0");
1855
+ }
1856
+ if (typeof error.code === "string" && /^\d{5}$/.test(error.code)) {
1857
+ return error.code;
1858
+ }
1859
+ return;
1860
+ }
1861
+ function mapDatabaseError(error) {
1862
+ if (error instanceof HttpError) {
1863
+ return error;
1864
+ }
1865
+ if (!isPostgresError(error)) {
1866
+ const message = error instanceof Error ? error.message : "Database operation failed.";
1867
+ return new BadRequestError(message);
1868
+ }
1869
+ const sqlState = getPostgresSqlState(error);
1870
+ switch (sqlState) {
1871
+ case "23505":
1872
+ return new ConflictError(error.detail ?? "A record with these values already exists.", {
1873
+ constraint: error.constraint
1874
+ });
1875
+ case "23503":
1876
+ return new UnprocessableEntityError(error.detail ?? "Referenced record does not exist.", {
1877
+ constraint: error.constraint
1878
+ });
1879
+ case "23502":
1880
+ return new BadRequestError(error.detail ?? "Required field is missing.", {
1881
+ constraint: error.constraint
1882
+ });
1883
+ case "23514":
1884
+ return new BadRequestError(error.detail ?? "Value violates a database constraint.", {
1885
+ constraint: error.constraint
1886
+ });
1887
+ default:
1888
+ return new BadRequestError(error.message ?? "Database operation failed.", {
1889
+ code: error.code,
1890
+ sqlState
1891
+ });
1892
+ }
1893
+ }
1894
+ async function withDatabaseErrorHandling(operation) {
1895
+ try {
1896
+ return await operation();
1897
+ } catch (error) {
1898
+ throw mapDatabaseError(error);
1899
+ }
1900
+ }
1901
+
1902
+ // ../../src/core/database/query.ts
1903
+ function quoteIdentifier(identifier) {
1904
+ if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(identifier)) {
1905
+ throw new Error(`Invalid SQL identifier: ${identifier}`);
1906
+ }
1907
+ return `"${identifier}"`;
1908
+ }
1909
+ function qualifyColumn(tableName, column) {
1910
+ return `${quoteIdentifier(tableName)}.${quoteIdentifier(column)}`;
1911
+ }
1912
+ function resolveQualifiedColumn(defaultTable, columnName) {
1913
+ if (columnName.includes(".")) {
1914
+ const [table, column] = columnName.split(".", 2);
1915
+ if (!table || !column) {
1916
+ throw new Error(`Invalid qualified column: ${columnName}`);
1917
+ }
1918
+ return qualifyColumn(table, column);
1919
+ }
1920
+ return qualifyColumn(defaultTable, columnName);
1921
+ }
1922
+ function parseQualifiedColumn(reference) {
1923
+ const [table, column] = reference.split(".", 2);
1924
+ if (!table || !column) {
1925
+ throw new Error(`Join columns must be qualified as table.column: ${reference}`);
1926
+ }
1927
+ return { table, column };
1928
+ }
1929
+ function normalizeDirection(direction = "ASC") {
1930
+ return direction.toUpperCase() === "DESC" ? "DESC" : "ASC";
1931
+ }
1932
+ function isQueryOperator(value) {
1933
+ return value !== null && !Array.isArray(value) && !(value instanceof Date) && typeof value === "object";
1934
+ }
1935
+ function pushParam(values, value) {
1936
+ values.push(value);
1937
+ return `$${values.length}`;
1938
+ }
1939
+ function buildInClause(column, values, params) {
1940
+ if (values.length === 0) {
1941
+ return "1 = 0";
1942
+ }
1943
+ const placeholders = values.map((value) => pushParam(params, value)).join(", ");
1944
+ return `${column} IN (${placeholders})`;
1945
+ }
1946
+ function buildOperatorClauses(column, operator, params) {
1947
+ const clauses = [];
1948
+ if (operator.isNull === true) {
1949
+ clauses.push(`${column} IS NULL`);
1950
+ }
1951
+ if (operator.isNull === false) {
1952
+ clauses.push(`${column} IS NOT NULL`);
1953
+ }
1954
+ if (operator.eq !== undefined) {
1955
+ if (operator.eq === null) {
1956
+ clauses.push(`${column} IS NULL`);
1957
+ } else {
1958
+ clauses.push(`${column} = ${pushParam(params, operator.eq)}`);
1959
+ }
1960
+ }
1961
+ if (operator.in !== undefined) {
1962
+ clauses.push(buildInClause(column, operator.in, params));
1963
+ }
1964
+ if (operator.gt !== undefined) {
1965
+ clauses.push(`${column} > ${pushParam(params, operator.gt)}`);
1966
+ }
1967
+ if (operator.gte !== undefined) {
1968
+ clauses.push(`${column} >= ${pushParam(params, operator.gte)}`);
1969
+ }
1970
+ if (operator.lt !== undefined) {
1971
+ clauses.push(`${column} < ${pushParam(params, operator.lt)}`);
1972
+ }
1973
+ if (operator.lte !== undefined) {
1974
+ clauses.push(`${column} <= ${pushParam(params, operator.lte)}`);
1975
+ }
1976
+ if (operator.ilike !== undefined) {
1977
+ clauses.push(`${column} ILIKE ${pushParam(params, `%${operator.ilike}%`)}`);
1978
+ }
1979
+ if (operator.tsMatch !== undefined) {
1980
+ clauses.push(`${column} @@ plainto_tsquery('english', ${pushParam(params, operator.tsMatch)})`);
1981
+ }
1982
+ return clauses;
1983
+ }
1984
+ function appendWhereParts(tableName, where, params) {
1985
+ const clauses = [];
1986
+ for (const [columnName, filterValue] of Object.entries(where)) {
1987
+ if (filterValue === undefined) {
1988
+ continue;
1989
+ }
1990
+ const column = resolveQualifiedColumn(tableName, columnName);
1991
+ if (Array.isArray(filterValue)) {
1992
+ clauses.push(buildInClause(column, filterValue, params));
1993
+ continue;
1994
+ }
1995
+ if (isQueryOperator(filterValue)) {
1996
+ clauses.push(...buildOperatorClauses(column, filterValue, params));
1997
+ continue;
1998
+ }
1999
+ if (filterValue === null) {
2000
+ clauses.push(`${column} IS NULL`);
2001
+ continue;
2002
+ }
2003
+ clauses.push(`${column} = ${pushParam(params, filterValue)}`);
2004
+ }
2005
+ return clauses.join(" AND ");
2006
+ }
2007
+ function buildWhereNodeClause(tableName, node, params) {
2008
+ if ("where" in node) {
2009
+ return appendWhereParts(tableName, node.where, params);
2010
+ }
2011
+ const grouped = buildWhereGroupClause(tableName, node.group, params);
2012
+ if (!grouped) {
2013
+ return "";
2014
+ }
2015
+ return grouped.includes(" OR ") ? `(${grouped})` : grouped;
2016
+ }
2017
+ function buildWhereGroupClause(tableName, nodes, params) {
2018
+ let result = "";
2019
+ for (const node of nodes) {
2020
+ const part = buildWhereNodeClause(tableName, node, params);
2021
+ if (!part) {
2022
+ continue;
2023
+ }
2024
+ if (!result) {
2025
+ result = part;
2026
+ continue;
2027
+ }
2028
+ result = node.kind === "or" ? `${result} OR ${part}` : `${result} AND ${part}`;
2029
+ }
2030
+ if (!result) {
2031
+ return "";
2032
+ }
2033
+ return result;
2034
+ }
2035
+ function buildAdvancedWhereClause(tableName, where = {}, whereNodes = []) {
2036
+ const params = [];
2037
+ const nodes = [];
2038
+ if (Object.keys(where).length > 0) {
2039
+ nodes.push({ kind: "and", where });
2040
+ }
2041
+ nodes.push(...whereNodes);
2042
+ const combined = buildWhereGroupClause(tableName, nodes, params);
2043
+ return {
2044
+ clause: combined ? ` WHERE ${combined}` : "",
2045
+ params
2046
+ };
2047
+ }
2048
+ function resolveSoftDeleteColumn(table) {
2049
+ if (!table.softDeletes) {
2050
+ return null;
2051
+ }
2052
+ if (table.softDeletes === true) {
2053
+ return "deleted_at";
2054
+ }
2055
+ return table.softDeletes.column ?? "deleted_at";
2056
+ }
2057
+ function appendSoftDeleteScope(table, options, clauses) {
2058
+ const column = resolveSoftDeleteColumn(table);
2059
+ if (!column) {
2060
+ return;
2061
+ }
2062
+ const qualifiedColumn = qualifyColumn(table.name, column);
2063
+ if (options.onlyTrashed) {
2064
+ clauses.push(`${qualifiedColumn} IS NOT NULL`);
2065
+ return;
2066
+ }
2067
+ if (!options.withTrashed) {
2068
+ clauses.push(`${qualifiedColumn} IS NULL`);
2069
+ }
2070
+ }
2071
+ function buildQueryWhereClause(table, options = {}, whereNodes = []) {
2072
+ const { clause, params } = buildAdvancedWhereClause(table.name, options.where ?? {}, whereNodes);
2073
+ const softDeleteClauses = [];
2074
+ appendSoftDeleteScope(table, options, softDeleteClauses);
2075
+ if (softDeleteClauses.length === 0) {
2076
+ return { clause, params };
2077
+ }
2078
+ const base = clause.replace(/^ WHERE /, "");
2079
+ const scope = softDeleteClauses.join(" AND ");
2080
+ return {
2081
+ clause: base ? ` WHERE (${base}) AND ${scope}` : ` WHERE ${scope}`,
2082
+ params
2083
+ };
2084
+ }
2085
+ function isQueryOrder(value) {
2086
+ return "column" in value;
2087
+ }
2088
+ function normalizeOrderBy(orderBy) {
2089
+ if (!orderBy) {
2090
+ return [];
2091
+ }
2092
+ if (Array.isArray(orderBy)) {
2093
+ return orderBy;
2094
+ }
2095
+ if (isQueryOrder(orderBy)) {
2096
+ return [orderBy];
2097
+ }
2098
+ return Object.entries(orderBy).map(([column, direction]) => ({
2099
+ column,
2100
+ direction
2101
+ }));
2102
+ }
2103
+ function buildOrderByClause(tableName, orderBy) {
2104
+ const parts = normalizeOrderBy(orderBy).map(({ column, direction }) => {
2105
+ return `${resolveQualifiedColumn(tableName, column)} ${normalizeDirection(direction)}`;
2106
+ });
2107
+ return parts.length > 0 ? ` ORDER BY ${parts.join(", ")}` : "";
2108
+ }
2109
+ function buildGroupByClause(tableName, groupBy) {
2110
+ if (!groupBy) {
2111
+ return "";
2112
+ }
2113
+ const columns = (Array.isArray(groupBy) ? groupBy : [groupBy]).map((column) => String(column));
2114
+ const parts = columns.map((column) => resolveQualifiedColumn(tableName, column));
2115
+ return parts.length > 0 ? ` GROUP BY ${parts.join(", ")}` : "";
2116
+ }
2117
+ function buildHavingClause(tableName, having, params) {
2118
+ if (!having) {
2119
+ return "";
2120
+ }
2121
+ const body = appendWhereParts(tableName, having, params);
2122
+ return body.length > 0 ? ` HAVING ${body}` : "";
2123
+ }
2124
+ function buildJoinClause(joins = []) {
2125
+ return joins.map((join3) => {
2126
+ const joinType = join3.type === "left" ? "LEFT JOIN" : "INNER JOIN";
2127
+ const onClause = join3.on.map(({ left, right }) => `${qualifyColumn(left.table, left.column)} = ${qualifyColumn(right.table, right.column)}`).join(" AND ");
2128
+ return ` ${joinType} ${quoteIdentifier(join3.table)} ON ${onClause}`;
2129
+ }).join("");
2130
+ }
2131
+ function buildLimitClause(limit) {
2132
+ if (limit === undefined) {
2133
+ return "";
2134
+ }
2135
+ if (!Number.isInteger(limit) || limit <= 0) {
2136
+ throw new Error("Query limit must be a positive integer.");
2137
+ }
2138
+ return ` LIMIT ${limit}`;
2139
+ }
2140
+ function buildOffsetClause(offset) {
2141
+ if (offset === undefined) {
2142
+ return "";
2143
+ }
2144
+ if (!Number.isInteger(offset) || offset < 0) {
2145
+ throw new Error("Query offset must be a non-negative integer.");
2146
+ }
2147
+ return ` OFFSET ${offset}`;
2148
+ }
2149
+ function buildReturningColumns(table) {
2150
+ return table.columns.map((column) => qualifyColumn(table.name, column)).join(", ");
2151
+ }
2152
+ function buildSelectList(table, select, params = []) {
2153
+ if (!select || select.length === 0) {
2154
+ return buildReturningColumns(table);
2155
+ }
2156
+ return select.map((item) => {
2157
+ if (item.kind === "column") {
2158
+ const column2 = qualifyColumn(item.table, item.column);
2159
+ return item.as ? `${column2} AS ${quoteIdentifier(item.as)}` : column2;
2160
+ }
2161
+ if (item.kind === "literalText") {
2162
+ return `${pushParam(params, item.value)}::text AS ${quoteIdentifier(item.as)}`;
2163
+ }
2164
+ const column = qualifyColumn(item.table, item.column);
2165
+ const placeholder = pushParam(params, item.query);
2166
+ return `ts_rank(${column}, plainto_tsquery('english', ${placeholder})) AS ${quoteIdentifier(item.as)}`;
2167
+ }).join(", ");
2168
+ }
2169
+ function getDefinedColumnEntries(table, values, options = {}) {
2170
+ const record = values;
2171
+ const excluded = new Set(options.exclude ?? []);
2172
+ return table.columns.flatMap((column) => {
2173
+ if (excluded.has(column) || !Object.hasOwn(record, column)) {
2174
+ return [];
2175
+ }
2176
+ const value = record[column];
2177
+ if (value === undefined) {
2178
+ return [];
2179
+ }
2180
+ return [[column, value]];
2181
+ });
2182
+ }
2183
+ function buildSelectQuery(table, options = {}, whereNodes = []) {
2184
+ const params = [];
2185
+ const columns = buildSelectList(table, options.select, params);
2186
+ const { clause, params: whereParams } = buildQueryWhereClause(table, options, whereNodes);
2187
+ params.push(...whereParams);
2188
+ const joins = buildJoinClause(options.joins);
2189
+ const groupBy = buildGroupByClause(table.name, options.groupBy);
2190
+ const havingClause = buildHavingClause(table.name, options.having, params);
2191
+ const orderBy = buildOrderByClause(table.name, options.orderBy ?? table.defaultOrderBy);
2192
+ const limit = buildLimitClause(options.limit);
2193
+ const offset = buildOffsetClause(options.offset);
2194
+ return {
2195
+ text: `SELECT ${columns} FROM ${quoteIdentifier(table.name)}${joins}${clause}${groupBy}${havingClause}${orderBy}${limit}${offset}`,
2196
+ params
2197
+ };
2198
+ }
2199
+ function buildCountQuery(table, where = {}, options = {}, whereNodes = []) {
2200
+ const params = [];
2201
+ const { clause, params: whereParams } = buildQueryWhereClause(table, {
2202
+ where,
2203
+ withTrashed: options.withTrashed,
2204
+ onlyTrashed: options.onlyTrashed
2205
+ }, whereNodes);
2206
+ params.push(...whereParams);
2207
+ const joins = buildJoinClause(options.joins);
2208
+ const groupBy = buildGroupByClause(table.name, options.groupBy);
2209
+ return {
2210
+ text: `SELECT COUNT(*) AS count FROM ${quoteIdentifier(table.name)}${joins}${clause}${groupBy}`,
2211
+ params
2212
+ };
2213
+ }
2214
+ function buildProjectionQuery(table, expression, alias, options = {}, whereNodes = []) {
2215
+ assertSafeProjectionExpression(expression);
2216
+ const params = [];
2217
+ const { clause, params: whereParams } = buildQueryWhereClause(table, options, whereNodes);
2218
+ params.push(...whereParams);
2219
+ const joins = buildJoinClause(options.joins);
2220
+ const groupBy = buildGroupByClause(table.name, options.groupBy);
2221
+ const orderBy = buildOrderByClause(table.name, options.orderBy);
2222
+ const limit = buildLimitClause(options.limit);
2223
+ return {
2224
+ text: `SELECT ${expression} AS ${quoteIdentifier(alias)} FROM ${quoteIdentifier(table.name)}${joins}${clause}${groupBy}${orderBy}${limit}`,
2225
+ params
2226
+ };
2227
+ }
2228
+ var SAFE_PROJECTION_EXPRESSION = /^(COUNT\(\*\)|(?:"[\w_]+"(?:\."[\w_]+")?)|(?:AVG|SUM|MIN|MAX)\((?:"[\w_]+"(?:\."[\w_]+")?)\))$/;
2229
+ function assertSafeProjectionExpression(expression) {
2230
+ if (!SAFE_PROJECTION_EXPRESSION.test(expression.trim())) {
2231
+ throw new Error(`Unsafe projection expression: ${expression}`);
2232
+ }
2233
+ }
2234
+ function buildGroupedCountQuery(table, column, where = {}, options = {}) {
2235
+ const qualifiedColumn = qualifyColumn(table.name, column);
2236
+ const { clause, params } = buildQueryWhereClause(table, {
2237
+ where,
2238
+ ...options
2239
+ });
2240
+ return {
2241
+ text: `SELECT ${qualifiedColumn} AS ${quoteIdentifier("value")}, COUNT(*) AS ${quoteIdentifier("count")} FROM ${quoteIdentifier(table.name)}${clause} GROUP BY ${qualifiedColumn} ORDER BY ${qualifiedColumn} ASC`,
2242
+ params
2243
+ };
2244
+ }
2245
+ function buildInsertQuery(table, values) {
2246
+ const entries = getDefinedColumnEntries(table, values);
2247
+ if (entries.length === 0) {
2248
+ throw new Error(`Cannot insert into ${table.name} without any column values.`);
2249
+ }
2250
+ const params = [];
2251
+ const columns = entries.map(([column]) => quoteIdentifier(column)).join(", ");
2252
+ const placeholders = entries.map(([, value]) => pushParam(params, value)).join(", ");
2253
+ const returningColumns = buildReturningColumns(table);
2254
+ return {
2255
+ text: `INSERT INTO ${quoteIdentifier(table.name)} (${columns}) VALUES (${placeholders}) RETURNING ${returningColumns}`,
2256
+ params
2257
+ };
2258
+ }
2259
+ function buildUpdateQuery(table, id, changes) {
2260
+ const entries = getDefinedColumnEntries(table, changes, {
2261
+ exclude: [table.primaryKey]
2262
+ });
2263
+ if (entries.length === 0) {
2264
+ throw new Error(`Cannot update ${table.name} without any changed column values.`);
2265
+ }
2266
+ const params = [];
2267
+ const setClause = entries.map(([column, value]) => `${quoteIdentifier(column)} = ${pushParam(params, value)}`).join(", ");
2268
+ const primaryKeyPlaceholder = pushParam(params, id);
2269
+ const returningColumns = buildReturningColumns(table);
2270
+ const scopeClauses = [];
2271
+ appendSoftDeleteScope(table, {}, scopeClauses);
2272
+ const scopeSuffix = scopeClauses.length > 0 ? ` AND ${scopeClauses.join(" AND ")}` : "";
2273
+ return {
2274
+ text: `UPDATE ${quoteIdentifier(table.name)} SET ${setClause} WHERE ${quoteIdentifier(table.primaryKey)} = ${primaryKeyPlaceholder}${scopeSuffix} RETURNING ${returningColumns}`,
2275
+ params
2276
+ };
2277
+ }
2278
+ function buildSoftDeleteByIdQuery(table, id, deletedAt) {
2279
+ const deletedAtColumn = resolveSoftDeleteColumn(table);
2280
+ if (!deletedAtColumn) {
2281
+ throw new Error(`Table ${table.name} does not support soft deletes.`);
2282
+ }
2283
+ const returningColumns = buildReturningColumns(table);
2284
+ const scopeClauses = [];
2285
+ appendSoftDeleteScope(table, {}, scopeClauses);
2286
+ const scopeSuffix = scopeClauses.length > 0 ? ` AND ${scopeClauses.join(" AND ")}` : "";
2287
+ return {
2288
+ text: `UPDATE ${quoteIdentifier(table.name)} SET ${quoteIdentifier(deletedAtColumn)} = $1 WHERE ${quoteIdentifier(table.primaryKey)} = $2${scopeSuffix} RETURNING ${returningColumns}`,
2289
+ params: [deletedAt, id]
2290
+ };
2291
+ }
2292
+ function buildRestoreByIdQuery(table, id) {
2293
+ const deletedAtColumn = resolveSoftDeleteColumn(table);
2294
+ if (!deletedAtColumn) {
2295
+ throw new Error(`Table ${table.name} does not support soft deletes.`);
2296
+ }
2297
+ const returningColumns = buildReturningColumns(table);
2298
+ return {
2299
+ text: `UPDATE ${quoteIdentifier(table.name)} SET ${quoteIdentifier(deletedAtColumn)} = $1 WHERE ${quoteIdentifier(table.primaryKey)} = $2 AND ${qualifyColumn(table.name, deletedAtColumn)} IS NOT NULL RETURNING ${returningColumns}`,
2300
+ params: [null, id]
2301
+ };
2302
+ }
2303
+ function buildDeleteByIdQuery(table, id) {
2304
+ return {
2305
+ text: `DELETE FROM ${quoteIdentifier(table.name)} WHERE ${quoteIdentifier(table.primaryKey)} = $1 RETURNING ${quoteIdentifier(table.primaryKey)} AS ${quoteIdentifier("deleted_id")}`,
2306
+ params: [id]
2307
+ };
2308
+ }
2309
+
2310
+ // ../../src/core/database/relationships.ts
2311
+ function indexHasManyRelation(parents, children, relation) {
2312
+ const groups = new Map;
2313
+ for (const parent of parents) {
2314
+ groups.set(parent[relation.localKey], []);
2315
+ }
2316
+ for (const child of children) {
2317
+ const key = child[relation.foreignKey];
2318
+ const group = groups.get(key);
2319
+ if (!group) {
2320
+ continue;
2321
+ }
2322
+ group.push(child);
2323
+ }
2324
+ return groups;
2325
+ }
2326
+ function indexBelongsToRelation(children, parents, relation) {
2327
+ const parentsById = new Map;
2328
+ for (const parent of parents) {
2329
+ parentsById.set(parent[relation.ownerKey], parent);
2330
+ }
2331
+ const result = new Map;
2332
+ for (const child of children) {
2333
+ const foreignKey = child[relation.foreignKey];
2334
+ const parent = parentsById.get(foreignKey);
2335
+ if (parent) {
2336
+ result.set(foreignKey, parent);
2337
+ }
2338
+ }
2339
+ return result;
2340
+ }
2341
+
2342
+ // ../../src/core/database/boundConnection.ts
2343
+ var boundConnectionHolder = {
2344
+ connection: null
2345
+ };
2346
+ function getBoundDatabaseConnection() {
2347
+ return boundConnectionHolder.connection;
2348
+ }
2349
+
2350
+ // ../../src/core/database/repositoryConnection.ts
2351
+ function resolveRepositoryConnection() {
2352
+ return getBoundDatabaseConnection() ?? connection_default;
2353
+ }
2354
+ var repositoryConnection = new Proxy({}, {
2355
+ get(_target, property) {
2356
+ const connection = resolveRepositoryConnection();
2357
+ const value = connection[property];
2358
+ return typeof value === "function" ? value.bind(connection) : value;
2359
+ }
2360
+ });
2361
+
2362
+ // ../../src/core/database/whereBuilder.ts
2363
+ class WhereBuilder {
2364
+ nodes = [];
2365
+ where(where) {
2366
+ this.nodes.push({ kind: "and", where });
2367
+ return this;
2368
+ }
2369
+ orWhere(where) {
2370
+ this.nodes.push({ kind: "or", where });
2371
+ return this;
2372
+ }
2373
+ whereGroup(fn) {
2374
+ const nested = new WhereBuilder;
2375
+ fn(nested);
2376
+ if (nested.nodes.length > 0) {
2377
+ this.nodes.push({ kind: "and", group: nested.nodes });
2378
+ }
2379
+ return this;
2380
+ }
2381
+ orWhereGroup(fn) {
2382
+ const nested = new WhereBuilder;
2383
+ fn(nested);
2384
+ if (nested.nodes.length > 0) {
2385
+ this.nodes.push({ kind: "or", group: nested.nodes });
2386
+ }
2387
+ return this;
2388
+ }
2389
+ }
2390
+
2391
+ // ../../src/core/database/repositoryQuery.ts
2392
+ class RepositoryQuery {
2393
+ repository;
2394
+ whereClause;
2395
+ queryOptions;
2396
+ eagerLoads = [];
2397
+ whereNodes = [];
2398
+ constructor(repository, whereClause = {}, queryOptions = {}) {
2399
+ this.repository = repository;
2400
+ this.whereClause = whereClause;
2401
+ this.queryOptions = queryOptions;
2402
+ }
2403
+ where(input) {
2404
+ if (typeof input === "function") {
2405
+ const builder = new WhereBuilder;
2406
+ input(builder);
2407
+ this.whereNodes.push(...builder.nodes);
2408
+ return this;
2409
+ }
2410
+ this.whereClause = { ...this.whereClause, ...input };
2411
+ return this;
2412
+ }
2413
+ orWhere(input) {
2414
+ if (typeof input === "function") {
2415
+ const builder = new WhereBuilder;
2416
+ input(builder);
2417
+ if (builder.nodes.length > 0) {
2418
+ this.whereNodes.push({ kind: "or", group: builder.nodes });
2419
+ }
2420
+ return this;
2421
+ }
2422
+ this.whereNodes.push({ kind: "or", where: input });
2423
+ return this;
2424
+ }
2425
+ orderBy(orderBy) {
2426
+ this.queryOptions = { ...this.queryOptions, orderBy };
2427
+ return this;
2428
+ }
2429
+ limit(limit) {
2430
+ this.queryOptions = { ...this.queryOptions, limit };
2431
+ return this;
2432
+ }
2433
+ offset(offset) {
2434
+ this.queryOptions = { ...this.queryOptions, offset };
2435
+ return this;
2436
+ }
2437
+ join(left, right) {
2438
+ return this.addJoin("inner", left, right);
2439
+ }
2440
+ leftJoin(left, right) {
2441
+ return this.addJoin("left", left, right);
2442
+ }
2443
+ groupBy(groupBy) {
2444
+ this.queryOptions = { ...this.queryOptions, groupBy };
2445
+ return this;
2446
+ }
2447
+ having(having) {
2448
+ this.queryOptions = { ...this.queryOptions, having };
2449
+ return this;
2450
+ }
2451
+ withHasMany(as, relation, childRepository, options = {}) {
2452
+ this.eagerLoads.push({
2453
+ kind: "hasMany",
2454
+ as,
2455
+ relation,
2456
+ repository: childRepository,
2457
+ options
2458
+ });
2459
+ return this;
2460
+ }
2461
+ withBelongsTo(as, relation, parentRepository, options = {}) {
2462
+ this.eagerLoads.push({
2463
+ kind: "belongsTo",
2464
+ as,
2465
+ relation,
2466
+ repository: parentRepository,
2467
+ options
2468
+ });
2469
+ return this;
2470
+ }
2471
+ async get() {
2472
+ const rows = await this.repository.findAll(this.buildOptions());
2473
+ return await this.attach(rows);
2474
+ }
2475
+ async first() {
2476
+ const rows = await this.get();
2477
+ return rows[0] ?? null;
2478
+ }
2479
+ async paginate(options) {
2480
+ return await this.repository.paginate({
2481
+ ...this.buildOptions(),
2482
+ page: options.page,
2483
+ perPage: options.perPage
2484
+ });
2485
+ }
2486
+ buildOptions() {
2487
+ return {
2488
+ ...this.queryOptions,
2489
+ where: this.whereClause,
2490
+ whereNodes: this.whereNodes
2491
+ };
2492
+ }
2493
+ addJoin(type, left, right) {
2494
+ const leftRef = parseQualifiedColumn(left);
2495
+ const rightRef = parseQualifiedColumn(right);
2496
+ const table = type === "inner" ? rightRef.table : rightRef.table;
2497
+ const joins = this.queryOptions.joins ?? [];
2498
+ const existing = joins.find((join3) => join3.table === table && join3.type === type);
2499
+ if (existing) {
2500
+ existing.on.push({ left: leftRef, right: rightRef });
2501
+ return this;
2502
+ }
2503
+ this.queryOptions = {
2504
+ ...this.queryOptions,
2505
+ joins: [
2506
+ ...joins,
2507
+ {
2508
+ type,
2509
+ table,
2510
+ on: [{ left: leftRef, right: rightRef }]
2511
+ }
2512
+ ]
2513
+ };
2514
+ return this;
2515
+ }
2516
+ async attach(rows) {
2517
+ if (rows.length === 0 || this.eagerLoads.length === 0) {
2518
+ return rows.map((row) => ({ ...row }));
2519
+ }
2520
+ let result = rows.map((row) => ({ ...row }));
2521
+ for (const load of this.eagerLoads) {
2522
+ if (load.kind === "hasMany") {
2523
+ const relation2 = load.relation;
2524
+ const grouped2 = await load.repository.withConnection(this.repository.getConnection()).loadHasManyForParents(rows, relation2, load.options);
2525
+ result = result.map((row) => ({
2526
+ ...row,
2527
+ [load.as]: grouped2.get(row[relation2.localKey]) ?? []
2528
+ }));
2529
+ continue;
2530
+ }
2531
+ const relation = load.relation;
2532
+ const grouped = await this.repository.loadBelongsToForParents(rows, relation, load.repository, load.options);
2533
+ result = result.map((row) => ({
2534
+ ...row,
2535
+ [load.as]: grouped.get(row[relation.foreignKey])
2536
+ }));
2537
+ }
2538
+ return result;
2539
+ }
2540
+ }
2541
+
2542
+ // ../../src/core/database/baseRepository.ts
2543
+ class BaseRepository5 {
2544
+ table;
2545
+ connection;
2546
+ constructor(table, connection = repositoryConnection) {
2547
+ this.table = table;
2548
+ this.connection = connection;
2549
+ }
2550
+ async findAll(options = {}) {
2551
+ return await withDatabaseErrorHandling(async () => {
2552
+ const { whereNodes, ...queryOptions } = options;
2553
+ const { text, params } = buildSelectQuery(this.table, queryOptions, whereNodes ?? []);
2554
+ return await this.connection.unsafe(text, params);
2555
+ });
2556
+ }
2557
+ async paginate(options) {
2558
+ const { whereNodes, where = {}, page, perPage, ...queryOptions } = options;
2559
+ const total = await this.countWhere(where, {
2560
+ withTrashed: options.withTrashed,
2561
+ onlyTrashed: options.onlyTrashed,
2562
+ joins: options.joins,
2563
+ groupBy: options.groupBy
2564
+ }, whereNodes);
2565
+ const offset = (page - 1) * perPage;
2566
+ const data = await this.findAll({
2567
+ ...queryOptions,
2568
+ where,
2569
+ whereNodes,
2570
+ limit: perPage,
2571
+ offset
2572
+ });
2573
+ return {
2574
+ data,
2575
+ meta: buildPaginationMeta({ page, perPage, total })
2576
+ };
2577
+ }
2578
+ async chunk(count, callback, options = {}) {
2579
+ if (!Number.isInteger(count) || count <= 0) {
2580
+ throw new Error("Chunk size must be a positive integer.");
2581
+ }
2582
+ let offset = 0;
2583
+ while (true) {
2584
+ const rows = await this.findAll({
2585
+ ...options,
2586
+ limit: count,
2587
+ offset
2588
+ });
2589
+ if (rows.length === 0) {
2590
+ return;
2591
+ }
2592
+ const shouldContinue = await callback(rows);
2593
+ if (shouldContinue === false || rows.length < count) {
2594
+ return;
2595
+ }
2596
+ offset += count;
2597
+ }
2598
+ }
2599
+ async cursorPaginate(options) {
2600
+ const {
2601
+ perPage,
2602
+ cursor,
2603
+ cursorColumn = this.table.primaryKey,
2604
+ direction = "asc",
2605
+ where = {},
2606
+ whereNodes,
2607
+ ...queryOptions
2608
+ } = options;
2609
+ if (!Number.isInteger(perPage) || perPage <= 0) {
2610
+ throw new Error("Cursor page size must be a positive integer.");
2611
+ }
2612
+ const cursorWhere = { ...where };
2613
+ if (cursor !== undefined) {
2614
+ cursorWhere[cursorColumn] = direction === "asc" ? { gt: cursor } : { lt: cursor };
2615
+ }
2616
+ const rows = await this.findAll({
2617
+ ...queryOptions,
2618
+ where: cursorWhere,
2619
+ whereNodes,
2620
+ orderBy: { [cursorColumn]: direction },
2621
+ limit: perPage + 1
2622
+ });
2623
+ const hasMore = rows.length > perPage;
2624
+ const data = hasMore ? rows.slice(0, perPage) : rows;
2625
+ const nextCursor = hasMore ? data[data.length - 1]?.[cursorColumn] ?? null : null;
2626
+ const prevCursor = cursor ?? null;
2627
+ return {
2628
+ data,
2629
+ meta: {
2630
+ per_page: perPage,
2631
+ next_cursor: nextCursor,
2632
+ prev_cursor: prevCursor,
2633
+ has_more: hasMore
2634
+ }
2635
+ };
2636
+ }
2637
+ async findById(id) {
2638
+ return await this.firstOrNull({
2639
+ [this.table.primaryKey]: id
2640
+ });
2641
+ }
2642
+ async findByIdOrThrow(id, errorFactory) {
2643
+ const record = await this.findById(id);
2644
+ if (record) {
2645
+ return record;
2646
+ }
2647
+ throw errorFactory?.(id) ?? new Error(`${this.table.name} ${String(id)} was not found.`);
2648
+ }
2649
+ async findByIds(ids) {
2650
+ const uniqueIds = [...new Set(ids)];
2651
+ if (uniqueIds.length === 0) {
2652
+ return [];
2653
+ }
2654
+ return await this.findWhere({
2655
+ [this.table.primaryKey]: uniqueIds
2656
+ });
2657
+ }
2658
+ async firstOrNull(where, options = {}) {
2659
+ const [record] = await this.findAll({ ...options, where, limit: 1 });
2660
+ return record ?? null;
2661
+ }
2662
+ async create(values) {
2663
+ return await withDatabaseErrorHandling(async () => {
2664
+ const { text, params } = buildInsertQuery(this.table, values);
2665
+ const [record] = await this.connection.unsafe(text, params);
2666
+ if (!record) {
2667
+ throw new Error(`Insert into ${this.table.name} did not return a record.`);
2668
+ }
2669
+ const entity = record;
2670
+ await eventBus.dispatch(modelEventName(this.table.name, "created"), entity);
2671
+ return entity;
2672
+ });
2673
+ }
2674
+ async updateById(id, changes) {
2675
+ return await withDatabaseErrorHandling(async () => {
2676
+ const { text, params } = buildUpdateQuery(this.table, id, changes);
2677
+ const [record] = await this.connection.unsafe(text, params);
2678
+ const entity = record ?? null;
2679
+ if (entity) {
2680
+ await eventBus.dispatch(modelEventName(this.table.name, "updated"), entity);
2681
+ }
2682
+ return entity;
2683
+ });
2684
+ }
2685
+ async updateByIdOrThrow(id, changes, errorFactory) {
2686
+ const record = await this.updateById(id, changes);
2687
+ if (record) {
2688
+ return record;
2689
+ }
2690
+ throw errorFactory?.(id) ?? new Error(`${this.table.name} ${String(id)} was not found.`);
2691
+ }
2692
+ async deleteById(id) {
2693
+ if (resolveSoftDeleteColumn(this.table)) {
2694
+ return await this.softDeleteById(id);
2695
+ }
2696
+ return await this.forceDeleteById(id);
2697
+ }
2698
+ async softDeleteById(id) {
2699
+ return await withDatabaseErrorHandling(async () => {
2700
+ const { text, params } = buildSoftDeleteByIdQuery(this.table, id, new Date);
2701
+ const [record] = await this.connection.unsafe(text, params);
2702
+ if (!record) {
2703
+ return false;
2704
+ }
2705
+ await eventBus.dispatch(modelEventName(this.table.name, "deleted"), record);
2706
+ return true;
2707
+ });
2708
+ }
2709
+ async forceDeleteById(id) {
2710
+ return await withDatabaseErrorHandling(async () => {
2711
+ const { text, params } = buildDeleteByIdQuery(this.table, id);
2712
+ const [row] = await this.connection.unsafe(text, params);
2713
+ if (!row) {
2714
+ return false;
2715
+ }
2716
+ await eventBus.dispatch(modelEventName(this.table.name, "force-deleted"), {
2717
+ id
2718
+ });
2719
+ return true;
2720
+ });
2721
+ }
2722
+ async restoreById(id) {
2723
+ return await withDatabaseErrorHandling(async () => {
2724
+ const { text, params } = buildRestoreByIdQuery(this.table, id);
2725
+ const [record] = await this.connection.unsafe(text, params);
2726
+ if (!record) {
2727
+ return null;
2728
+ }
2729
+ const entity = record;
2730
+ await eventBus.dispatch(modelEventName(this.table.name, "restored"), entity);
2731
+ return entity;
2732
+ });
2733
+ }
2734
+ withConnection(connection) {
2735
+ const clone = Object.create(Object.getPrototypeOf(this));
2736
+ Object.assign(clone, this);
2737
+ clone.connection = connection;
2738
+ return clone;
2739
+ }
2740
+ getConnection() {
2741
+ return this.connection;
2742
+ }
2743
+ getTable() {
2744
+ return this.table;
2745
+ }
2746
+ query(where = {}) {
2747
+ return new RepositoryQuery(this, where);
2748
+ }
2749
+ async findWhere(where, options = {}) {
2750
+ return await this.findAll({ ...options, where });
2751
+ }
2752
+ async countWhere(where = {}, options = {}, whereNodes = []) {
2753
+ const { text, params } = buildCountQuery(this.table, where, options, whereNodes);
2754
+ const [row] = await this.connection.unsafe(text, params);
2755
+ return Number(row?.count ?? 0);
2756
+ }
2757
+ async averageColumn(column, where = {}) {
2758
+ const qualifiedColumn = qualifyColumn(this.table.name, column);
2759
+ return await this.averageExpression(`AVG(${qualifiedColumn})`, "value", where);
2760
+ }
2761
+ async averageExpression(expression, alias, where = {}) {
2762
+ const { text, params } = buildProjectionQuery(this.table, expression, alias, { where });
2763
+ const [row] = await this.connection.unsafe(text, params);
2764
+ return Math.round(Number(row?.[alias] ?? 0));
2765
+ }
2766
+ async pluckNumberValues(expression, alias, options = {}) {
2767
+ const { text, params } = buildProjectionQuery(this.table, expression, alias, options);
2768
+ const rows = await this.connection.unsafe(text, params);
2769
+ return rows.flatMap((row) => {
2770
+ const value = row[alias];
2771
+ return value === null || value === undefined ? [] : [Number(value)];
2772
+ });
2773
+ }
2774
+ async countGroupedBy(column, where = {}) {
2775
+ const { text, params } = buildGroupedCountQuery(this.table, column, where);
2776
+ const rows = await this.connection.unsafe(text, params);
2777
+ return rows.map(({ value, count }) => ({
2778
+ value,
2779
+ count: Number(count)
2780
+ }));
2781
+ }
2782
+ async findByHasManyRelation(relation, parentId, options = {}) {
2783
+ return await this.findWhere({
2784
+ [relation.foreignKey]: parentId
2785
+ }, options);
2786
+ }
2787
+ async loadHasManyForParents(parents, relation, options = {}) {
2788
+ if (parents.length === 0) {
2789
+ return indexHasManyRelation(parents, [], relation);
2790
+ }
2791
+ const parentIds = [...new Set(parents.map((parent) => parent[relation.localKey]))];
2792
+ const children = await this.findWhere({
2793
+ [relation.foreignKey]: parentIds
2794
+ }, options);
2795
+ return indexHasManyRelation(parents, children, relation);
2796
+ }
2797
+ async loadBelongsToForParents(children, relation, parentRepository, options = {}) {
2798
+ if (children.length === 0) {
2799
+ return new Map;
2800
+ }
2801
+ const ownerIds = [...new Set(children.map((child) => child[relation.foreignKey]))];
2802
+ const parents = await parentRepository.withConnection(this.connection).findWhere({
2803
+ [relation.ownerKey]: ownerIds
2804
+ }, options);
2805
+ return indexBelongsToRelation(children, parents, relation);
2806
+ }
2807
+ }
2808
+ var baseRepository_default = BaseRepository5;
2809
+ // ../../src/core/database/model.ts
2810
+ var modelRepositories = new WeakMap;
2811
+ var modelGlobalScopes = new WeakMap;
2812
+ var modelBooted = new WeakSet;
2813
+ // ../../src/core/database/schema/columnDefinition.ts
2814
+ class ColumnDefinition {
2815
+ name;
2816
+ kind;
2817
+ length;
2818
+ isNullable = false;
2819
+ isPrimary = false;
2820
+ isUnique = false;
2821
+ autoIncrement = false;
2822
+ defaultValue;
2823
+ checkExpression;
2824
+ foreignKey;
2825
+ constructor(name, kind) {
2826
+ this.name = name;
2827
+ this.kind = kind;
2828
+ }
2829
+ nullable() {
2830
+ this.isNullable = true;
2831
+ return this;
2832
+ }
2833
+ notNullable() {
2834
+ this.isNullable = false;
2835
+ return this;
2836
+ }
2837
+ default(value) {
2838
+ if (typeof value === "boolean") {
2839
+ this.defaultValue = value ? "TRUE" : "FALSE";
2840
+ return this;
2841
+ }
2842
+ if (typeof value === "number") {
2843
+ this.defaultValue = String(value);
2844
+ return this;
2845
+ }
2846
+ this.defaultValue = `'${value.replace(/'/g, "''")}'`;
2847
+ return this;
2848
+ }
2849
+ defaultRaw(expression) {
2850
+ this.defaultValue = expression;
2851
+ return this;
2852
+ }
2853
+ unique() {
2854
+ this.isUnique = true;
2855
+ return this;
2856
+ }
2857
+ primary() {
2858
+ this.isPrimary = true;
2859
+ return this;
2860
+ }
2861
+ check(expression) {
2862
+ this.checkExpression = expression;
2863
+ return this;
2864
+ }
2865
+ }
2866
+
2867
+ class ForeignIdColumnDefinition extends ColumnDefinition {
2868
+ constructor(name) {
2869
+ super(name, "foreignId");
2870
+ this.notNullable();
2871
+ }
2872
+ references(table, column = "id") {
2873
+ this.foreignKey = {
2874
+ referencesTable: table,
2875
+ referencesColumn: column
2876
+ };
2877
+ return this;
2878
+ }
2879
+ constrained(table) {
2880
+ const referencesTable = table ?? inferReferencedTable(this.name);
2881
+ return this.references(referencesTable);
2882
+ }
2883
+ cascadeOnDelete() {
2884
+ if (!this.foreignKey) {
2885
+ throw new Error(`Foreign key is not defined for column ${this.name}`);
2886
+ }
2887
+ this.foreignKey.onDelete = "cascade";
2888
+ return this;
2889
+ }
2890
+ nullOnDelete() {
2891
+ if (!this.foreignKey) {
2892
+ throw new Error(`Foreign key is not defined for column ${this.name}`);
2893
+ }
2894
+ this.foreignKey.onDelete = "set null";
2895
+ return this;
2896
+ }
2897
+ }
2898
+ function inferReferencedTable(columnName) {
2899
+ if (!columnName.endsWith("_id")) {
2900
+ throw new Error(`Cannot infer referenced table from column ${columnName}`);
2901
+ }
2902
+ return columnName.slice(0, -3);
2903
+ }
2904
+
2905
+ // ../../src/core/database/schema/blueprint.ts
2906
+ class Blueprint {
2907
+ table;
2908
+ action;
2909
+ columns = [];
2910
+ indexes = [];
2911
+ droppedColumns = [];
2912
+ droppedIndexes = [];
2913
+ constructor(table, action) {
2914
+ this.table = table;
2915
+ this.action = action;
2916
+ }
2917
+ id(name = "id") {
2918
+ const column = new ColumnDefinition(name, "id");
2919
+ column.primary();
2920
+ column.autoIncrement = true;
2921
+ this.columns.push(column);
2922
+ return column;
2923
+ }
2924
+ string(name, length) {
2925
+ const column = new ColumnDefinition(name, "string");
2926
+ column.length = length;
2927
+ column.notNullable();
2928
+ this.columns.push(column);
2929
+ return column;
2930
+ }
2931
+ text(name) {
2932
+ const column = new ColumnDefinition(name, "text");
2933
+ column.notNullable();
2934
+ this.columns.push(column);
2935
+ return column;
2936
+ }
2937
+ boolean(name) {
2938
+ const column = new ColumnDefinition(name, "boolean");
2939
+ column.notNullable();
2940
+ this.columns.push(column);
2941
+ return column;
2942
+ }
2943
+ integer(name) {
2944
+ const column = new ColumnDefinition(name, "integer");
2945
+ column.notNullable();
2946
+ this.columns.push(column);
2947
+ return column;
2948
+ }
2949
+ bigInteger(name) {
2950
+ const column = new ColumnDefinition(name, "bigInteger");
2951
+ column.notNullable();
2952
+ this.columns.push(column);
2953
+ return column;
2954
+ }
2955
+ timestamp(name) {
2956
+ const column = new ColumnDefinition(name, "timestamp");
2957
+ column.notNullable();
2958
+ this.columns.push(column);
2959
+ return column;
2960
+ }
2961
+ json(name) {
2962
+ const column = new ColumnDefinition(name, "json");
2963
+ column.notNullable();
2964
+ this.columns.push(column);
2965
+ return column;
2966
+ }
2967
+ jsonb(name) {
2968
+ const column = new ColumnDefinition(name, "jsonb");
2969
+ column.notNullable();
2970
+ this.columns.push(column);
2971
+ return column;
2972
+ }
2973
+ foreignId(name) {
2974
+ const column = new ForeignIdColumnDefinition(name);
2975
+ this.columns.push(column);
2976
+ return column;
2977
+ }
2978
+ timestamps() {
2979
+ this.timestamp("created_at").defaultRaw("NOW()");
2980
+ this.timestamp("updated_at").defaultRaw("NOW()");
2981
+ }
2982
+ softDeletes() {
2983
+ this.timestamp("deleted_at").nullable();
2984
+ }
2985
+ dropColumn(name) {
2986
+ this.droppedColumns.push(name);
2987
+ }
2988
+ dropSoftDeletes() {
2989
+ this.dropColumn("deleted_at");
2990
+ this.dropIndex(`idx_${this.table}_deleted_at`);
2991
+ }
2992
+ dropIndex(name) {
2993
+ this.droppedIndexes.push(name);
2994
+ }
2995
+ unique(columns, name) {
2996
+ this.indexes.push({
2997
+ name,
2998
+ columns: Array.isArray(columns) ? columns : [columns],
2999
+ kind: "unique"
3000
+ });
3001
+ }
3002
+ index(columns, options = {}) {
3003
+ this.indexes.push({
3004
+ name: options.name,
3005
+ columns: Array.isArray(columns) ? columns : [columns],
3006
+ kind: "index",
3007
+ order: options.order
3008
+ });
3009
+ }
3010
+ partialIndex(columns, where, nameOrOptions) {
3011
+ const options = typeof nameOrOptions === "string" ? { name: nameOrOptions } : nameOrOptions ?? {};
3012
+ this.indexes.push({
3013
+ name: options.name,
3014
+ columns: Array.isArray(columns) ? columns : [columns],
3015
+ kind: options.unique ? "uniquePartial" : "partial",
3016
+ where
3017
+ });
3018
+ }
3019
+ fullText(columns, name) {
3020
+ this.indexes.push({
3021
+ name,
3022
+ columns: Array.isArray(columns) ? columns : [columns],
3023
+ kind: "fullText"
3024
+ });
3025
+ }
3026
+ ginIndex(column, name) {
3027
+ this.indexes.push({
3028
+ name,
3029
+ columns: [column],
3030
+ kind: "gin"
3031
+ });
3032
+ }
3033
+ }
3034
+ // ../../src/core/database/schema/errors.ts
3035
+ class UnsupportedSchemaFeatureError extends Error {
3036
+ constructor(feature, driver) {
3037
+ super(`${feature} is not supported for the ${driver} driver`);
3038
+ this.name = "UnsupportedSchemaFeatureError";
3039
+ }
3040
+ }
3041
+ // ../../src/core/database/schema/grammars/grammar.ts
3042
+ function compileColumnType(driver, column) {
3043
+ switch (column.kind) {
3044
+ case "id":
3045
+ return compileIdType(driver);
3046
+ case "string":
3047
+ return compileStringType(driver, column.length);
3048
+ case "text":
3049
+ return compileTextType(driver);
3050
+ case "boolean":
3051
+ return compileBooleanType(driver);
3052
+ case "integer":
3053
+ case "foreignId":
3054
+ return compileIntegerType(driver);
3055
+ case "bigInteger":
3056
+ return compileBigIntegerType(driver);
3057
+ case "timestamp":
3058
+ return compileTimestampType(driver);
3059
+ case "json":
3060
+ return compileJsonType(driver);
3061
+ case "jsonb":
3062
+ return compileJsonbType(driver);
3063
+ default:
3064
+ throw new Error(`Unsupported column kind: ${column.kind}`);
3065
+ }
3066
+ }
3067
+ function compileIdType(driver) {
3068
+ switch (driver) {
3069
+ case "pgsql":
3070
+ return "SERIAL";
3071
+ case "mysql":
3072
+ return "BIGINT UNSIGNED";
3073
+ case "sqlite":
3074
+ return "INTEGER";
3075
+ }
3076
+ }
3077
+ function compileStringType(driver, length) {
3078
+ switch (driver) {
3079
+ case "pgsql":
3080
+ return "TEXT";
3081
+ case "mysql":
3082
+ return length ? `VARCHAR(${length})` : "VARCHAR(255)";
3083
+ case "sqlite":
3084
+ return "TEXT";
3085
+ }
3086
+ }
3087
+ function compileTextType(driver) {
3088
+ switch (driver) {
3089
+ case "pgsql":
3090
+ case "sqlite":
3091
+ return "TEXT";
3092
+ case "mysql":
3093
+ return "TEXT";
3094
+ }
3095
+ }
3096
+ function compileBooleanType(driver) {
3097
+ switch (driver) {
3098
+ case "pgsql":
3099
+ return "BOOLEAN";
3100
+ case "mysql":
3101
+ return "BOOLEAN";
3102
+ case "sqlite":
3103
+ return "INTEGER";
3104
+ }
3105
+ }
3106
+ function compileIntegerType(driver) {
3107
+ switch (driver) {
3108
+ case "pgsql":
3109
+ return "INTEGER";
3110
+ case "mysql":
3111
+ return "INT";
3112
+ case "sqlite":
3113
+ return "INTEGER";
3114
+ }
3115
+ }
3116
+ function compileBigIntegerType(driver) {
3117
+ switch (driver) {
3118
+ case "pgsql":
3119
+ return "BIGINT";
3120
+ case "mysql":
3121
+ return "BIGINT";
3122
+ case "sqlite":
3123
+ return "INTEGER";
3124
+ }
3125
+ }
3126
+ function compileTimestampType(driver) {
3127
+ switch (driver) {
3128
+ case "pgsql":
3129
+ return "TIMESTAMPTZ";
3130
+ case "mysql":
3131
+ return "TIMESTAMP";
3132
+ case "sqlite":
3133
+ return "TEXT";
3134
+ }
3135
+ }
3136
+ function compileJsonType(driver) {
3137
+ switch (driver) {
3138
+ case "pgsql":
3139
+ return "JSONB";
3140
+ case "mysql":
3141
+ return "JSON";
3142
+ case "sqlite":
3143
+ return "TEXT";
3144
+ }
3145
+ }
3146
+ function compileJsonbType(driver) {
3147
+ switch (driver) {
3148
+ case "pgsql":
3149
+ return "JSONB";
3150
+ case "mysql":
3151
+ return "JSON";
3152
+ case "sqlite":
3153
+ return "TEXT";
3154
+ }
3155
+ }
3156
+
3157
+ // ../../src/core/database/schema/grammars/compileStatements.ts
3158
+ function compileCreateTable(driver, blueprint) {
3159
+ const table = quoteIdentifier(blueprint.table);
3160
+ const parts = blueprint.columns.map((column) => compileColumn(driver, column, "create"));
3161
+ for (const index of blueprint.indexes) {
3162
+ if (index.kind === "unique" && index.columns.length > 1) {
3163
+ const columns = index.columns.map((column) => quoteIdentifier(column)).join(", ");
3164
+ parts.push(`UNIQUE (${columns})`);
3165
+ }
3166
+ }
3167
+ const statements = [`CREATE TABLE IF NOT EXISTS ${table} (
3168
+ ${parts.join(`,
3169
+ `)}
3170
+ )`];
3171
+ for (const index of blueprint.indexes) {
3172
+ if (index.kind === "unique" && index.columns.length === 1) {
3173
+ continue;
3174
+ }
3175
+ if (index.kind === "index") {
3176
+ statements.push(compileIndex(driver, blueprint.table, index));
3177
+ } else if (index.kind === "partial" || index.kind === "uniquePartial" || index.kind === "gin" || index.kind === "fullText") {
3178
+ statements.push(...compileSpecialIndex(driver, blueprint.table, index));
3179
+ }
3180
+ }
3181
+ return statements;
3182
+ }
3183
+ function compileAlterTable(driver, blueprint) {
3184
+ const statements = [];
3185
+ const table = quoteIdentifier(blueprint.table);
3186
+ for (const column of blueprint.columns) {
3187
+ const addPrefix = driver === "pgsql" ? "ADD COLUMN IF NOT EXISTS" : "ADD COLUMN";
3188
+ statements.push(`ALTER TABLE ${table}
3189
+ ${addPrefix} ${compileColumn(driver, column, "alter")}`);
3190
+ }
3191
+ for (const columnName of blueprint.droppedColumns) {
3192
+ const dropPrefix = driver === "pgsql" ? "DROP COLUMN IF EXISTS" : "DROP COLUMN";
3193
+ statements.push(`ALTER TABLE ${table} ${dropPrefix} ${quoteIdentifier(columnName)}`);
3194
+ }
3195
+ for (const indexName of blueprint.droppedIndexes) {
3196
+ statements.push(`DROP INDEX IF EXISTS ${quoteIdentifier(indexName)}`);
3197
+ }
3198
+ for (const index of blueprint.indexes) {
3199
+ if (index.kind === "index" || index.kind === "unique") {
3200
+ statements.push(compileIndex(driver, blueprint.table, index));
3201
+ } else {
3202
+ statements.push(...compileSpecialIndex(driver, blueprint.table, index));
3203
+ }
3204
+ }
3205
+ return statements;
3206
+ }
3207
+ function compileDropTable(driver, tableName) {
3208
+ const cascade = driver === "pgsql" ? " CASCADE" : "";
3209
+ return [`DROP TABLE IF EXISTS ${quoteIdentifier(tableName)}${cascade}`];
3210
+ }
3211
+ function compileColumn(driver, column, mode) {
3212
+ const parts = [quoteIdentifier(column.name), compileColumnType(driver, column)];
3213
+ if (column.autoIncrement && driver === "mysql") {
3214
+ parts[1] = `${parts[1]} AUTO_INCREMENT`;
3215
+ }
3216
+ if (column.isPrimary && mode === "create") {
3217
+ if (driver === "sqlite") {
3218
+ parts.push("PRIMARY KEY AUTOINCREMENT");
3219
+ } else {
3220
+ parts.push("PRIMARY KEY");
3221
+ }
3222
+ } else if (!column.isNullable) {
3223
+ parts.push("NOT NULL");
3224
+ } else if (column.isNullable) {
3225
+ parts.push("NULL");
3226
+ }
3227
+ if (column.defaultValue !== undefined) {
3228
+ parts.push(`DEFAULT ${column.defaultValue}`);
3229
+ }
3230
+ if (column.isUnique) {
3231
+ parts.push("UNIQUE");
3232
+ }
3233
+ if (column.checkExpression) {
3234
+ parts.push(`CHECK (${column.checkExpression})`);
3235
+ }
3236
+ if (column.foreignKey) {
3237
+ const { referencesTable, referencesColumn, onDelete } = column.foreignKey;
3238
+ const reference = `${quoteIdentifier(referencesTable)}(${quoteIdentifier(referencesColumn)})`;
3239
+ let clause = `REFERENCES ${reference}`;
3240
+ if (onDelete === "cascade") {
3241
+ clause += " ON DELETE CASCADE";
3242
+ } else if (onDelete === "set null") {
3243
+ clause += " ON DELETE SET NULL";
3244
+ }
3245
+ parts.push(clause);
3246
+ }
3247
+ return parts.join(" ");
3248
+ }
3249
+ function compileIndex(_driver, tableName, index) {
3250
+ const indexName = index.name ?? defaultIndexName(tableName, index.columns, index.kind === "unique" ? "unique" : "index");
3251
+ const columns = index.columns.map((column) => {
3252
+ const quoted = quoteIdentifier(column);
3253
+ if (index.order === "desc") {
3254
+ return `${quoted} DESC`;
3255
+ }
3256
+ return quoted;
3257
+ }).join(", ");
3258
+ const unique = index.kind === "unique" ? "UNIQUE " : "";
3259
+ return `CREATE ${unique}INDEX IF NOT EXISTS ${quoteIdentifier(indexName)} ON ${quoteIdentifier(tableName)}(${columns})`;
3260
+ }
3261
+ function compileSpecialIndex(driver, tableName, index) {
3262
+ const indexName = index.name ?? defaultIndexName(tableName, index.columns, index.kind);
3263
+ const columns = index.columns.map((column) => quoteIdentifier(column)).join(", ");
3264
+ switch (index.kind) {
3265
+ case "partial":
3266
+ case "uniquePartial": {
3267
+ if (driver !== "pgsql") {
3268
+ throw new UnsupportedSchemaFeatureError("partialIndex()", driver);
3269
+ }
3270
+ const unique = index.kind === "uniquePartial" ? "UNIQUE " : "";
3271
+ return [
3272
+ `CREATE ${unique}INDEX IF NOT EXISTS ${quoteIdentifier(indexName)} ON ${quoteIdentifier(tableName)}(${columns}) WHERE ${index.where}`
3273
+ ];
3274
+ }
3275
+ case "gin": {
3276
+ if (driver !== "pgsql") {
3277
+ throw new UnsupportedSchemaFeatureError("ginIndex()", driver);
3278
+ }
3279
+ return [
3280
+ `CREATE INDEX IF NOT EXISTS ${quoteIdentifier(indexName)} ON ${quoteIdentifier(tableName)} USING GIN(${columns})`
3281
+ ];
3282
+ }
3283
+ case "fullText": {
3284
+ if (driver === "mysql") {
3285
+ return [
3286
+ `CREATE FULLTEXT INDEX ${quoteIdentifier(indexName)} ON ${quoteIdentifier(tableName)}(${columns})`
3287
+ ];
3288
+ }
3289
+ if (driver === "pgsql") {
3290
+ throw new UnsupportedSchemaFeatureError("fullText(); use ginIndex() with a tsvector column on PostgreSQL", driver);
3291
+ }
3292
+ throw new UnsupportedSchemaFeatureError("fullText()", driver);
3293
+ }
3294
+ default:
3295
+ return [];
3296
+ }
3297
+ }
3298
+ function defaultIndexName(tableName, columns, kind) {
3299
+ return `idx_${tableName}_${columns.join("_")}_${kind}`;
3300
+ }
3301
+ function compileBlueprint(driver, blueprint) {
3302
+ switch (blueprint.action) {
3303
+ case "create":
3304
+ return compileCreateTable(driver, blueprint);
3305
+ case "alter":
3306
+ return compileAlterTable(driver, blueprint);
3307
+ case "drop":
3308
+ return compileDropTable(driver, blueprint.table);
3309
+ default:
3310
+ throw new Error(`Unsupported blueprint action: ${blueprint.action}`);
3311
+ }
3312
+ }
3313
+ // ../../src/core/database/schema/grammars/createGrammar.ts
3314
+ function createGrammar(driver) {
3315
+ return {
3316
+ driver,
3317
+ compile(blueprint) {
3318
+ return compileBlueprint(driver, blueprint);
3319
+ }
3320
+ };
3321
+ }
3322
+
3323
+ // ../../src/core/database/schema/grammars/mysqlGrammar.ts
3324
+ var MySqlGrammar = createGrammar("mysql");
3325
+
3326
+ // ../../src/core/database/schema/grammars/postgresGrammar.ts
3327
+ var PostgresGrammar = createGrammar("pgsql");
3328
+
3329
+ // ../../src/core/database/schema/grammars/sqliteGrammar.ts
3330
+ var SqliteGrammar = createGrammar("sqlite");
3331
+
3332
+ // ../../src/core/database/schema/grammars/index.ts
3333
+ function grammarForDriver(driver) {
3334
+ switch (driver) {
3335
+ case "pgsql":
3336
+ return PostgresGrammar;
3337
+ case "mysql":
3338
+ return MySqlGrammar;
3339
+ case "sqlite":
3340
+ return SqliteGrammar;
3341
+ default:
3342
+ throw new Error(`Unsupported database driver: ${driver}`);
3343
+ }
3344
+ }
3345
+ // ../../src/core/database/schema/schema.ts
3346
+ class SchemaBuilder {
3347
+ #driver;
3348
+ #statements = [];
3349
+ constructor(driver) {
3350
+ this.#driver = driver;
3351
+ }
3352
+ create(table, callback) {
3353
+ const blueprint = new Blueprint(table, "create");
3354
+ callback(blueprint);
3355
+ this.#statements.push(...grammarForDriver(this.#driver).compile(blueprint));
3356
+ return this;
3357
+ }
3358
+ table(table, callback) {
3359
+ const blueprint = new Blueprint(table, "alter");
3360
+ callback(blueprint);
3361
+ this.#statements.push(...grammarForDriver(this.#driver).compile(blueprint));
3362
+ return this;
3363
+ }
3364
+ drop(table) {
3365
+ const blueprint = new Blueprint(table, "drop");
3366
+ this.#statements.push(...grammarForDriver(this.#driver).compile(blueprint));
3367
+ return this;
3368
+ }
3369
+ toSql() {
3370
+ return [...this.#statements];
3371
+ }
3372
+ async execute(db2) {
3373
+ for (const statement of this.#statements) {
3374
+ await db2.unsafe(statement);
3375
+ }
3376
+ }
3377
+ }
3378
+ // ../../src/core/database/table.ts
3379
+ function defineTable5(definition) {
3380
+ return definition;
3381
+ }
3382
+ // ../../src/core/queue/failedJobTable.ts
3383
+ var failedJobTable = defineTable5({
3384
+ name: "failed_job",
3385
+ primaryKey: "id",
3386
+ columns: ["id", "job_name", "payload", "exception", "failed_at"],
3387
+ defaultOrderBy: { column: "failed_at", direction: "DESC" }
3388
+ });
3389
+
3390
+ // ../../src/core/queue/failedJobRepository.ts
3391
+ class FailedJobRepository extends baseRepository_default {
3392
+ constructor() {
3393
+ super(failedJobTable);
3394
+ }
3395
+ }
3396
+ var failedJobRepository_default = FailedJobRepository;
3397
+
3398
+ // ../../src/core/queue/failedJobService.ts
3399
+ class FailedJobService {
3400
+ repository;
3401
+ constructor(repository) {
3402
+ this.repository = repository;
3403
+ }
3404
+ async recordFailure(input) {
3405
+ return await this.repository.create({
3406
+ job_name: input.jobName,
3407
+ payload: input.payload,
3408
+ exception: input.exception,
3409
+ failed_at: new Date
3410
+ });
3411
+ }
3412
+ listRecent(limit = 50) {
3413
+ return this.repository.findAll({
3414
+ limit,
3415
+ orderBy: { column: "failed_at", direction: "DESC" }
3416
+ });
3417
+ }
3418
+ async retry(id) {
3419
+ const failedJob = await this.repository.findByIdOrThrow(id, (jobId) => new Error(`Failed job ${jobId} not found.`));
3420
+ await this.repository.deleteById(id);
3421
+ return failedJob;
3422
+ }
3423
+ async flush() {
3424
+ const jobs = await this.repository.findAll();
3425
+ let deleted = 0;
3426
+ for (const job of jobs) {
3427
+ if (await this.repository.deleteById(job.id)) {
3428
+ deleted += 1;
3429
+ }
3430
+ }
3431
+ return deleted;
3432
+ }
3433
+ }
3434
+ var failedJobService_default = FailedJobService;
3435
+
3436
+ // ../../src/core/queue/redisQueue.ts
3437
+ var {RedisClient: RedisClient2 } = globalThis.Bun;
3438
+
3439
+ // ../../src/core/queue/jobRunner.ts
3440
+ async function runQueueJob(envelope, failedJobs) {
3441
+ const job = jobRegistry.create(envelope.name);
3442
+ if (!job) {
3443
+ throw new Error(`Unknown job "${envelope.name}".`);
3444
+ }
3445
+ const attempts = envelope.attempts ?? 0;
3446
+ try {
3447
+ await job.handle(envelope.payload);
3448
+ } catch (error) {
3449
+ const nextAttempt = attempts + 1;
3450
+ const maxAttempts = job.maxAttempts ?? queueConfig.maxAttempts;
3451
+ if (nextAttempt < maxAttempts) {
3452
+ const backoffMs = job.backoffMs ?? queueConfig.backoffMs;
3453
+ await new Promise((resolve) => setTimeout(resolve, backoffMs * nextAttempt));
3454
+ await runQueueJob({
3455
+ ...envelope,
3456
+ attempts: nextAttempt
3457
+ }, failedJobs);
3458
+ return;
3459
+ }
3460
+ await failedJobs.recordFailure({
3461
+ jobName: envelope.name,
3462
+ payload: envelope.payload,
3463
+ exception: error instanceof Error ? error.stack ?? error.message : String(error)
3464
+ });
3465
+ throw error;
3466
+ }
3467
+ }
3468
+
3469
+ // ../../src/core/queue/redisQueue.ts
3470
+ var QUEUE_LIST_KEY = "workhub:queue:default";
3471
+ var QUEUE_HIGH_KEY = "workhub:queue:high";
3472
+ var QUEUE_LOW_KEY = "workhub:queue:low";
3473
+ function queueKeyForPriority(priority = "default") {
3474
+ switch (priority) {
3475
+ case "high":
3476
+ return QUEUE_HIGH_KEY;
3477
+ case "low":
3478
+ return QUEUE_LOW_KEY;
3479
+ default:
3480
+ return QUEUE_LIST_KEY;
3481
+ }
3482
+ }
3483
+ class RedisQueue {
3484
+ client;
3485
+ constructor(redisUrl) {
3486
+ this.client = new RedisClient2(redisUrl);
3487
+ }
3488
+ async dispatch(job, payload) {
3489
+ const name = jobRegistry.resolveName(job);
3490
+ if (!name) {
3491
+ throw new Error("Job is not registered with the queue worker registry.");
3492
+ }
3493
+ const envelope = {
3494
+ name,
3495
+ payload,
3496
+ attempts: 0
3497
+ };
3498
+ const queueKey = queueKeyForPriority(job.priority);
3499
+ await this.client.lpush(queueKey, JSON.stringify(envelope));
3500
+ }
3501
+ }
3502
+
3503
+ // ../../src/core/queue/resilientQueue.ts
3504
+ class ResilientQueue {
3505
+ failedJobs;
3506
+ asyncDispatch;
3507
+ constructor(failedJobs, asyncDispatch = false) {
3508
+ this.failedJobs = failedJobs;
3509
+ this.asyncDispatch = asyncDispatch;
3510
+ }
3511
+ async dispatch(job, payload) {
3512
+ const name = jobRegistry.resolveName(job);
3513
+ if (!name) {
3514
+ throw new Error("Job is not registered with the queue worker registry.");
3515
+ }
3516
+ const envelope = {
3517
+ name,
3518
+ payload,
3519
+ attempts: 0
3520
+ };
3521
+ if (this.asyncDispatch) {
3522
+ setTimeout(() => {
3523
+ runQueueJob(envelope, this.failedJobs).catch((error) => {
3524
+ console.error("[ResilientQueue] Job failed:", error);
3525
+ });
3526
+ }, 0);
3527
+ return;
3528
+ }
3529
+ await runQueueJob(envelope, this.failedJobs);
3530
+ }
3531
+ }
3532
+
3533
+ // ../../src/core/queue/publicQueue.ts
3534
+ function createFailedJobService() {
3535
+ return new failedJobService_default(new failedJobRepository_default);
3536
+ }
3537
+ function createTrackedJob(name, job) {
3538
+ return jobRegistry.track(name, job);
3539
+ }
3540
+ function createProductionQueue(driver, options = {}) {
3541
+ options.registerJobs?.();
3542
+ const failedJobs = options.failedJobs ?? createFailedJobService();
3543
+ if (driver === "redis") {
3544
+ if (!options.redisUrl) {
3545
+ throw new Error('QUEUE_DRIVER="redis" requires REDIS_URL to be set.');
3546
+ }
3547
+ return new RedisQueue(options.redisUrl);
3548
+ }
3549
+ return new ResilientQueue(failedJobs, driver === "async");
3550
+ }
3551
+
3552
+ // ../../src/core/queue/createAppQueue.ts
3553
+ var FAILED_JOB_SERVICE_TOKEN = "core.failedJobs";
3554
+ function registerDefaultJobs() {
3555
+ jobRegistry.register("cache.invalidate-tags", () => {
3556
+ return new invalidateCacheTagsJob_default(resolveApplicationCache());
3557
+ });
3558
+ jobRegistry.register("webhook.dispatch", () => new dispatchWebhookJob_default);
3559
+ }
3560
+ function createAppQueue(driver, redisUrl, failedJobs = createFailedJobService()) {
3561
+ return createProductionQueue(driver, {
3562
+ redisUrl,
3563
+ failedJobs,
3564
+ registerJobs: registerDefaultJobs
3565
+ });
3566
+ }
3567
+
3568
+ // ../../src/bootstrap/listeners/invalidateCacheOnModelWrite.ts
3569
+ var MODEL_WRITE_ACTIONS = ["created", "updated", "deleted", "restored", "force-deleted"];
3570
+ function registerInvalidateCacheOnModelWriteListeners(bus = eventBus) {
3571
+ for (const tableName of discoverModelTableNames()) {
3572
+ for (const action of MODEL_WRITE_ACTIONS) {
3573
+ bus.listen(modelEventName(tableName, action), async () => {
3574
+ const tags = cacheTagsForModelWrite(tableName, action);
3575
+ if (tags.length === 0) {
3576
+ return;
3577
+ }
3578
+ const cache = resolveApplicationCache();
3579
+ const queue = resolveApplicationQueue();
3580
+ const job = createTrackedJob("cache.invalidate-tags", new invalidateCacheTagsJob_default(cache));
3581
+ await queue.dispatch(job, { tags });
3582
+ });
3583
+ }
3584
+ }
3585
+ }
3586
+
3587
+ // ../../src/bootstrap/providers/listeners.ts
3588
+ var registeredListenerGroups = new Set;
3589
+ function registerListenerGroup(name, register) {
3590
+ if (registeredListenerGroups.has(name)) {
3591
+ return;
3592
+ }
3593
+ registeredListenerGroups.add(name);
3594
+ register();
3595
+ }
3596
+ var listenersProvider = {
3597
+ name: "core.listeners",
3598
+ boot() {
3599
+ registerListenerGroup("cache.invalidate-on-model-write", () => {
3600
+ registerInvalidateCacheOnModelWriteListeners();
3601
+ });
3602
+ for (const [index, registerListener] of discoverListeners().entries()) {
3603
+ registerListenerGroup(`app.listener.${index}`, registerListener);
3604
+ }
3605
+ }
3606
+ };
3607
+ var listeners_default = listenersProvider;
3608
+
3609
+ // ../../src/core/auth/policy.ts
3610
+ var BLOCKED_POLICY_ACTIONS = new Set([
3611
+ "constructor",
3612
+ "toString",
3613
+ "valueOf",
3614
+ "hasOwnProperty",
3615
+ "isPrototypeOf",
3616
+ "propertyIsEnumerable",
3617
+ "__proto__"
3618
+ ]);
3619
+
3620
+ class PolicyGate {
3621
+ constructor() {}
3622
+ policies = new Map;
3623
+ register(resource, policy) {
3624
+ this.policies.set(resource, policy);
3625
+ }
3626
+ allows(resource, action, user, model) {
3627
+ const policy = this.policies.get(resource);
3628
+ if (!policy) {
3629
+ return false;
3630
+ }
3631
+ if (BLOCKED_POLICY_ACTIONS.has(action) || !(action in policy)) {
3632
+ return false;
3633
+ }
3634
+ const handler = policy[action];
3635
+ if (typeof handler !== "function") {
3636
+ return false;
3637
+ }
3638
+ const resolvedUser = user === undefined ? currentAuthUser() : user;
3639
+ return model === undefined ? handler.call(policy, resolvedUser) : handler.call(policy, resolvedUser, model);
3640
+ }
3641
+ authorize(resource, action, user, model) {
3642
+ if (!this.allows(resource, action, user, model)) {
3643
+ throw new ForbiddenError;
3644
+ }
3645
+ }
3646
+ }
3647
+
3648
+ // ../../src/bootstrap/providers/policy.ts
3649
+ var policyProvider = {
3650
+ name: "core.policy",
3651
+ register({ container }) {
3652
+ container.set(CORE_POLICY_GATE_TOKEN, new PolicyGate);
3653
+ }
3654
+ };
3655
+ var policy_default = policyProvider;
3656
+
3657
+ // ../../src/bootstrap/providers/queue.ts
3658
+ var queueProvider = {
3659
+ name: "core.queue",
3660
+ register({ container, config }) {
3661
+ const configuredDriver = process.env.QUEUE_DRIVER ?? DEFAULT_QUEUE_DRIVER;
3662
+ const driver = configuredDriver === "async" || configuredDriver === "redis" || configuredDriver === "sync" ? configuredDriver : DEFAULT_QUEUE_DRIVER;
3663
+ config.set("queue.driver", driver);
3664
+ const failedJobs = createFailedJobService();
3665
+ container.set(FAILED_JOB_SERVICE_TOKEN, failedJobs);
3666
+ container.set(CORE_QUEUE_TOKEN, createAppQueue(driver, config.get(REDIS_URL_CONFIG_KEY) ?? process.env.REDIS_URL, failedJobs));
3667
+ }
3668
+ };
3669
+ var queue_default = queueProvider;
3670
+
3671
+ // ../../src/config/frontend.ts
3672
+ function readFrontendMode() {
3673
+ const mode = (process.env.FRONTEND_MODE ?? "api").trim();
3674
+ if (mode === "server-htmx") {
3675
+ return "server-htmx";
3676
+ }
3677
+ if (mode === "spa-react") {
3678
+ return "spa-react";
3679
+ }
3680
+ return "api";
3681
+ }
3682
+ function isViewsEnabled() {
3683
+ return readFrontendMode() === "server-htmx";
3684
+ }
3685
+
3686
+ // ../../src/core/http/requestMetaContext.ts
3687
+ import { AsyncLocalStorage as AsyncLocalStorage3 } from "async_hooks";
3688
+ var requestMetaContext = new AsyncLocalStorage3;
3689
+ function runWithRequestMeta(meta, callback) {
3690
+ return requestMetaContext.run(meta, callback);
3691
+ }
3692
+ function currentRequestMeta() {
3693
+ return requestMetaContext.getStore() ?? {
3694
+ ipAddress: null,
3695
+ userAgent: null
3696
+ };
3697
+ }
3698
+
3699
+ // ../../src/core/view/etaViewEngine.ts
3700
+ import { join as join3 } from "path";
3701
+ import { Eta } from "eta";
3702
+ var DEFAULT_VIEWS_DIRECTORY = join3(process.cwd(), "resources/views");
3703
+ var DEFAULT_LAYOUT = "layouts/app.eta";
3704
+
3705
+ class EtaViewEngine {
3706
+ eta;
3707
+ resolveLayoutData;
3708
+ constructor(viewsDirectory = DEFAULT_VIEWS_DIRECTORY, resolveLayoutData) {
3709
+ this.eta = new Eta({
3710
+ views: viewsDirectory,
3711
+ autoTrim: false
3712
+ });
3713
+ this.resolveLayoutData = resolveLayoutData;
3714
+ }
3715
+ async render(name, data = {}, options = {}) {
3716
+ const template = name.endsWith(".eta") ? name : `${name}.eta`;
3717
+ const layoutData = this.resolveLayoutData ? await this.resolveLayoutData() : {};
3718
+ const mergedData = { ...layoutData, ...data };
3719
+ const body = await this.eta.renderAsync(template, mergedData);
3720
+ const layout = options.layout ?? DEFAULT_LAYOUT;
3721
+ if (layout === false) {
3722
+ return body;
3723
+ }
3724
+ const layoutTemplate = layout.endsWith(".eta") ? layout : `${layout}.eta`;
3725
+ return await this.eta.renderAsync(layoutTemplate, {
3726
+ ...mergedData,
3727
+ body
3728
+ });
3729
+ }
3730
+ }
3731
+ // ../../src/core/view/htmlResponse.ts
3732
+ function htmlResponse(html, init = {}) {
3733
+ return new Response(html, {
3734
+ status: init.status ?? 200,
3735
+ statusText: init.statusText,
3736
+ headers: {
3737
+ "Content-Type": "text/html; charset=utf-8"
3738
+ }
3739
+ });
3740
+ }
3741
+ // ../../src/core/http/csrfToken.ts
3742
+ import { createHmac as createHmac3, randomBytes, timingSafeEqual as timingSafeEqual2 } from "crypto";
3743
+ var CSRF_COOKIE = "workhub_csrf";
3744
+ var CSRF_TTL_MS = 60 * 60 * 1000;
3745
+ function resolveCsrfSecret() {
3746
+ return process.env.SESSION_SECRET?.trim() || process.env.OAUTH_STATE_SECRET?.trim() || process.env.ADMIN_API_TOKEN?.trim() || "workhub-dev-csrf-secret";
3747
+ }
3748
+ function signCsrfToken(token, issuedAt) {
3749
+ const payload = `${token}.${issuedAt}`;
3750
+ const signature = createHmac3("sha256", resolveCsrfSecret()).update(payload).digest("hex");
3751
+ return `${payload}.${signature}`;
3752
+ }
3753
+ function readCsrfCookie(request) {
3754
+ const cookieHeader = request.headers.get("cookie");
3755
+ if (!cookieHeader) {
3756
+ return null;
3757
+ }
3758
+ for (const part of cookieHeader.split(";")) {
3759
+ const [name, ...rest] = part.trim().split("=");
3760
+ if (name === CSRF_COOKIE) {
3761
+ return decodeURIComponent(rest.join("="));
3762
+ }
3763
+ }
3764
+ return null;
3765
+ }
3766
+ function parseSignedCsrfValue(cookieValue) {
3767
+ const parts = cookieValue.split(".");
3768
+ if (parts.length !== 3) {
3769
+ return null;
3770
+ }
3771
+ const [token, issuedAtRaw, cookieSignature] = parts;
3772
+ if (!token || !issuedAtRaw || !cookieSignature) {
3773
+ return null;
3774
+ }
3775
+ const issuedAt = Number.parseInt(issuedAtRaw, 10);
3776
+ if (!Number.isFinite(issuedAt)) {
3777
+ return null;
3778
+ }
3779
+ if (Date.now() - issuedAt > CSRF_TTL_MS) {
3780
+ return null;
3781
+ }
3782
+ const expectedSignature = signCsrfToken(token, issuedAt).split(".").pop();
3783
+ if (!expectedSignature) {
3784
+ return null;
3785
+ }
3786
+ const expectedBuffer = Buffer.from(expectedSignature);
3787
+ const actualBuffer = Buffer.from(cookieSignature);
3788
+ if (expectedBuffer.length !== actualBuffer.length) {
3789
+ return null;
3790
+ }
3791
+ if (!timingSafeEqual2(expectedBuffer, actualBuffer)) {
3792
+ return null;
3793
+ }
3794
+ return { token, issuedAt };
3795
+ }
3796
+ function createCsrfTokenCookie() {
3797
+ const token = randomBytes(24).toString("hex");
3798
+ const issuedAt = Date.now();
3799
+ const value = signCsrfToken(token, issuedAt);
3800
+ return {
3801
+ token,
3802
+ cookie: `${CSRF_COOKIE}=${encodeURIComponent(value)}; Path=/; SameSite=Lax; Max-Age=3600`
3803
+ };
3804
+ }
3805
+ function resolveCsrfToken(request) {
3806
+ const cookieValue = readCsrfCookie(request);
3807
+ if (cookieValue) {
3808
+ const parsed = parseSignedCsrfValue(cookieValue);
3809
+ if (parsed) {
3810
+ return { token: parsed.token };
3811
+ }
3812
+ }
3813
+ return createCsrfTokenCookie();
3814
+ }
3815
+ function readSubmittedCsrfToken(request) {
3816
+ const headerToken = request.headers.get("x-csrf-token")?.trim();
3817
+ if (headerToken) {
3818
+ return headerToken;
3819
+ }
3820
+ return null;
3821
+ }
3822
+ async function readSubmittedCsrfTokenFromBody(request) {
3823
+ const headerToken = readSubmittedCsrfToken(request);
3824
+ if (headerToken) {
3825
+ return headerToken;
3826
+ }
3827
+ const contentType = request.headers.get("content-type")?.toLowerCase() ?? "";
3828
+ if (contentType.includes("application/x-www-form-urlencoded") || contentType.includes("multipart/form-data")) {
3829
+ const formData = await request.clone().formData();
3830
+ const field = formData.get("_token");
3831
+ if (typeof field === "string" && field.trim().length > 0) {
3832
+ return field.trim();
3833
+ }
3834
+ }
3835
+ return null;
3836
+ }
3837
+ function verifyCsrfToken(request, submittedToken) {
3838
+ if (!submittedToken) {
3839
+ return false;
3840
+ }
3841
+ const cookieValue = readCsrfCookie(request);
3842
+ if (!cookieValue) {
3843
+ return false;
3844
+ }
3845
+ const parsed = parseSignedCsrfValue(cookieValue);
3846
+ if (!parsed) {
3847
+ return false;
3848
+ }
3849
+ const submittedBuffer = Buffer.from(submittedToken);
3850
+ const expectedBuffer = Buffer.from(parsed.token);
3851
+ if (submittedBuffer.length !== expectedBuffer.length) {
3852
+ return false;
3853
+ }
3854
+ return timingSafeEqual2(submittedBuffer, expectedBuffer);
3855
+ }
3856
+ function resolveCsrfTokenForRequest(request) {
3857
+ const metaToken = currentRequestMeta().csrfToken;
3858
+ if (metaToken) {
3859
+ return metaToken;
3860
+ }
3861
+ return resolveCsrfToken(request).token;
3862
+ }
3863
+
3864
+ // ../../src/core/http/flashSession.ts
3865
+ import { createHmac as createHmac4, timingSafeEqual as timingSafeEqual3 } from "crypto";
3866
+ var FLASH_COOKIE = "workhub_flash";
3867
+ var FLASH_TTL_MS = 60 * 1000;
3868
+ function resolveFlashSecret() {
3869
+ return process.env.SESSION_SECRET?.trim() || process.env.OAUTH_STATE_SECRET?.trim() || "workhub-dev-flash-secret";
3870
+ }
3871
+ function signFlashPayload(payload, issuedAt) {
3872
+ const signature = createHmac4("sha256", resolveFlashSecret()).update(`${payload}.${issuedAt}`).digest("hex");
3873
+ return `${payload}.${issuedAt}.${signature}`;
3874
+ }
3875
+ function readFlashCookie(request) {
3876
+ const cookieHeader = request.headers.get("cookie");
3877
+ if (!cookieHeader) {
3878
+ return null;
3879
+ }
3880
+ for (const part of cookieHeader.split(";")) {
3881
+ const [name, ...rest] = part.trim().split("=");
3882
+ if (name === FLASH_COOKIE) {
3883
+ return decodeURIComponent(rest.join("="));
3884
+ }
3885
+ }
3886
+ return null;
3887
+ }
3888
+ function parseFlashCookie(cookieValue) {
3889
+ const parts = cookieValue.split(".");
3890
+ if (parts.length < 3) {
3891
+ return null;
3892
+ }
3893
+ const signature = parts.pop();
3894
+ const issuedAtRaw = parts.pop();
3895
+ const payload = parts.join(".");
3896
+ if (!signature || !issuedAtRaw || !payload) {
3897
+ return null;
3898
+ }
3899
+ const issuedAt = Number.parseInt(issuedAtRaw, 10);
3900
+ if (!Number.isFinite(issuedAt) || Date.now() - issuedAt > FLASH_TTL_MS) {
3901
+ return null;
3902
+ }
3903
+ const expectedSignature = signFlashPayload(payload, issuedAt).split(".").pop();
3904
+ if (!expectedSignature) {
3905
+ return null;
3906
+ }
3907
+ const expectedBuffer = Buffer.from(expectedSignature);
3908
+ const actualBuffer = Buffer.from(signature);
3909
+ if (expectedBuffer.length !== actualBuffer.length) {
3910
+ return null;
3911
+ }
3912
+ if (!timingSafeEqual3(expectedBuffer, actualBuffer)) {
3913
+ return null;
3914
+ }
3915
+ try {
3916
+ const parsed = JSON.parse(Buffer.from(payload, "base64url").toString("utf8"));
3917
+ if (!parsed?.message || typeof parsed.message !== "string") {
3918
+ return null;
3919
+ }
3920
+ if (parsed.level !== "success" && parsed.level !== "error" && parsed.level !== "info") {
3921
+ return null;
3922
+ }
3923
+ return parsed;
3924
+ } catch {
3925
+ return null;
3926
+ }
3927
+ }
3928
+ function clearFlashCookie() {
3929
+ return `${FLASH_COOKIE}=; Path=/; HttpOnly; SameSite=Lax; Max-Age=0`;
3930
+ }
3931
+ function pullFlash(request) {
3932
+ const cookieValue = readFlashCookie(request);
3933
+ if (!cookieValue) {
3934
+ return null;
3935
+ }
3936
+ return parseFlashCookie(cookieValue);
3937
+ }
3938
+ function withFlashClear(response) {
3939
+ const headers = new Headers(response.headers);
3940
+ headers.append("set-cookie", clearFlashCookie());
3941
+ return new Response(response.body, {
3942
+ status: response.status,
3943
+ statusText: response.statusText,
3944
+ headers
3945
+ });
3946
+ }
3947
+
3948
+ // ../../src/core/view/webLayoutData.ts
3949
+ async function resolveWebLayoutData(container, request) {
3950
+ const csrfToken = request ? resolveCsrfTokenForRequest(request) : "";
3951
+ const flash = request ? currentRequestMeta().flash ?? pullFlash(request) : null;
3952
+ const authUser = currentAuthUser();
3953
+ if (!authUser) {
3954
+ return { authUser: null, csrfToken, flash };
3955
+ }
3956
+ const userId = Number(authUser.id);
3957
+ if (!Number.isInteger(userId) || userId <= 0) {
3958
+ return { authUser: null, csrfToken, flash };
3959
+ }
3960
+ if (!container.has(tokenServiceToken)) {
3961
+ return {
3962
+ authUser: {
3963
+ id: userId,
3964
+ email: "",
3965
+ role: authUser.role ?? "member"
3966
+ },
3967
+ csrfToken,
3968
+ flash
3969
+ };
3970
+ }
3971
+ const tokenService = container.resolve(tokenServiceToken);
3972
+ try {
3973
+ const user = await tokenService.findByIdOrThrow(userId);
3974
+ return {
3975
+ authUser: {
3976
+ id: userId,
3977
+ email: user.email ?? "",
3978
+ role: authUser.role ?? user.role ?? "member"
3979
+ },
3980
+ csrfToken,
3981
+ flash
3982
+ };
3983
+ } catch {
3984
+ return { authUser: null, csrfToken, flash };
3985
+ }
3986
+ }
3987
+ // ../../src/bootstrap/providers/view.ts
3988
+ var CORE_VIEW_TOKEN = "core.view";
3989
+ var VIEW_DIRECTORY_CONFIG_KEY = "view.directory";
3990
+ var viewProvider = {
3991
+ name: "view",
3992
+ register({ container, config }) {
3993
+ if (!isViewsEnabled()) {
3994
+ return;
3995
+ }
3996
+ const viewsDirectory = process.env.VIEW_DIRECTORY?.trim() || DEFAULT_VIEWS_DIRECTORY;
3997
+ config.set(VIEW_DIRECTORY_CONFIG_KEY, viewsDirectory);
3998
+ container.set(CORE_VIEW_TOKEN, new EtaViewEngine(viewsDirectory, () => resolveWebLayoutData(container, currentRequestMeta().request)));
3999
+ }
4000
+ };
4001
+
4002
+ // ../../src/bootstrap/providers/index.ts
4003
+ var coreProviders = [
4004
+ config_default,
4005
+ cache_default,
4006
+ auth_default,
4007
+ events_default,
4008
+ policy_default,
4009
+ queue_default,
4010
+ listeners_default,
4011
+ viewProvider
4012
+ ];
4013
+
4014
+ // ../../src/domain/auth.ts
4015
+ var TEST_ADMIN_API_TOKEN = "workhub-admin-test-token";
4016
+ var TEST_MEMBER_API_TOKEN = "workhub-member-test-token";
4017
+
4018
+ // ../../src/domain/scim.ts
4019
+ var TEST_SCIM_BEARER_TOKEN = "workhub-scim-test-token";
4020
+ var DEFAULT_SCIM_BEARER_TOKEN = TEST_SCIM_BEARER_TOKEN;
4021
+
4022
+ // ../../src/bootstrap/secretsGuard.ts
4023
+ var DEFAULT_TOKENS = new Set([TEST_ADMIN_API_TOKEN, TEST_MEMBER_API_TOKEN]);
4024
+ var DEFAULT_SCIM_TOKENS = new Set([TEST_SCIM_BEARER_TOKEN, DEFAULT_SCIM_BEARER_TOKEN]);
4025
+ function assertProductionSecrets(env = process.env) {
4026
+ const appEnv = env.APP_ENV ?? appConfig.env;
4027
+ if (appEnv !== "production") {
4028
+ return;
4029
+ }
4030
+ const adminToken = env.ADMIN_API_TOKEN ?? TEST_ADMIN_API_TOKEN;
4031
+ const memberToken = env.MEMBER_API_TOKEN ?? TEST_MEMBER_API_TOKEN;
4032
+ const scimToken = env.SCIM_BEARER_TOKEN ?? DEFAULT_SCIM_BEARER_TOKEN;
4033
+ const encryptionEnabled = env.FEATURE_FIELD_ENCRYPTION !== "false";
4034
+ const devHeadersEnabled = (env.AUTH_DEV_HEADERS ?? "true") !== "false";
4035
+ if (devHeadersEnabled) {
4036
+ throw new Error("Production startup blocked: set AUTH_DEV_HEADERS=false to disable development auth headers.");
4037
+ }
4038
+ if (DEFAULT_TOKENS.has(adminToken) || DEFAULT_TOKENS.has(memberToken)) {
4039
+ throw new Error("Production startup blocked: rotate ADMIN_API_TOKEN and MEMBER_API_TOKEN away from default WorkHub test values.");
4040
+ }
4041
+ if (DEFAULT_SCIM_TOKENS.has(scimToken)) {
4042
+ throw new Error("Production startup blocked: rotate SCIM_BEARER_TOKEN away from default WorkHub test values.");
4043
+ }
4044
+ if (encryptionEnabled && !env.KMS_ENCRYPTION_KEY?.trim()) {
4045
+ throw new Error("Production startup blocked: set KMS_ENCRYPTION_KEY when field encryption is enabled.");
4046
+ }
4047
+ if (!env.SIEM_EXPORT_URL?.trim() && isFeatureEnabled("siemExport")) {
4048
+ console.warn("[secrets] SIEM_EXPORT_URL is not configured; audit logs remain database-only.");
4049
+ }
4050
+ const billingEnabled = (env.FEATURE_BILLING ?? "true") !== "false";
4051
+ if (billingEnabled && !env.STRIPE_WEBHOOK_SECRET?.trim()) {
4052
+ throw new Error("Production startup blocked: set STRIPE_WEBHOOK_SECRET when billing webhooks are enabled.");
4053
+ }
4054
+ const corsOrigins = (env.CORS_ALLOWED_ORIGINS ?? "*").split(",").map((origin) => origin.trim());
4055
+ if (corsOrigins.includes("*")) {
4056
+ throw new Error("Production startup blocked: set explicit CORS_ALLOWED_ORIGINS instead of wildcard.");
4057
+ }
4058
+ if ((env.FEATURE_PUBLIC_READS ?? "true") !== "false") {
4059
+ throw new Error("Production startup blocked: set FEATURE_PUBLIC_READS=false for authenticated-only reads.");
4060
+ }
4061
+ if (!env.OAUTH_STATE_SECRET?.trim()) {
4062
+ throw new Error("Production startup blocked: set OAUTH_STATE_SECRET for OAuth CSRF protection.");
4063
+ }
4064
+ if (!env.TOKEN_HASH_PEPPER?.trim()) {
4065
+ throw new Error("Production startup blocked: set TOKEN_HASH_PEPPER for API token hashing.");
4066
+ }
4067
+ if (!env.API_TOKEN_DEFAULT_EXPIRY_DAYS?.trim()) {
4068
+ throw new Error("Production startup blocked: set API_TOKEN_DEFAULT_EXPIRY_DAYS to enforce token rotation.");
4069
+ }
4070
+ }
4071
+
4072
+ // ../../src/bootstrap/context.ts
4073
+ function collectProviders(modules = appModules) {
4074
+ return [...coreProviders, ...modules.flatMap((module) => module.providers ?? [])];
4075
+ }
4076
+ function runProviderPhase(providers, phase, context) {
4077
+ for (const provider of providers) {
4078
+ provider[phase]?.(context);
4079
+ }
4080
+ }
4081
+ function createAppContext() {
4082
+ assertProductionSecrets();
4083
+ const container = new ServiceContainer;
4084
+ const config = new ConfigStore;
4085
+ const dependencies = {
4086
+ container
4087
+ };
4088
+ const context = {
4089
+ container,
4090
+ config,
4091
+ dependencies
4092
+ };
4093
+ const providers = collectProviders();
4094
+ runProviderPhase(providers, "register", context);
4095
+ runProviderPhase(providers, "boot", context);
4096
+ assertAppDependenciesComplete(dependencies);
4097
+ const appContext = {
4098
+ container,
4099
+ config,
4100
+ dependencies
4101
+ };
4102
+ setActiveApplicationContext(appContext);
4103
+ return appContext;
4104
+ }
4105
+ var appContext = createAppContext();
4106
+ // ../../src/bootstrap/createWebRoutes.ts
4107
+ import { join as join4 } from "path";
4108
+
4109
+ // ../../src/core/http/middleware.ts
4110
+ function isRouteHandler(value) {
4111
+ return typeof value === "function";
4112
+ }
4113
+ function isMethodRouteMap(value) {
4114
+ if (value === null || typeof value !== "object" || Array.isArray(value)) {
4115
+ return false;
4116
+ }
4117
+ const entries = Object.entries(value);
4118
+ return entries.length > 0 && entries.every(([, handler]) => isRouteHandler(handler));
4119
+ }
4120
+ function composeMiddleware(...middleware) {
4121
+ return (handler) => {
4122
+ return async (request) => {
4123
+ let index = 0;
4124
+ const dispatch = async () => {
4125
+ if (index >= middleware.length) {
4126
+ return await handler(request);
4127
+ }
4128
+ const current = middleware[index];
4129
+ index += 1;
4130
+ if (!current) {
4131
+ return await handler(request);
4132
+ }
4133
+ return await current(request, dispatch);
4134
+ };
4135
+ return await dispatch();
4136
+ };
4137
+ };
4138
+ }
4139
+ async function requestIdMiddleware(request, next) {
4140
+ const requestId = request.headers.get("x-request-id") ?? crypto.randomUUID();
4141
+ const response = await next();
4142
+ const headers = new Headers(response.headers);
4143
+ headers.set("x-request-id", requestId);
4144
+ return new Response(response.body, {
4145
+ status: response.status,
4146
+ statusText: response.statusText,
4147
+ headers
4148
+ });
4149
+ }
4150
+ function wrapRouteHandler(handler, middleware) {
4151
+ if (isMethodRouteMap(handler)) {
4152
+ const wrapped = {};
4153
+ for (const [method, routeHandler] of Object.entries(handler)) {
4154
+ wrapped[method] = composeMiddleware(...middleware)(routeHandler);
4155
+ }
4156
+ return wrapped;
153
4157
  }
154
- if (mode === "spa-react") {
155
- return "spa-react";
4158
+ if (isRouteHandler(handler)) {
4159
+ return composeMiddleware(...middleware)(handler);
156
4160
  }
157
- return "api";
4161
+ return handler;
158
4162
  }
159
- function isViewsEnabled() {
160
- return readFrontendMode() === "server-htmx";
4163
+ function applyMiddlewareToRoutes(routes, middleware) {
4164
+ const wrapped = {};
4165
+ for (const [path, routeHandler] of Object.entries(routes)) {
4166
+ wrapped[path] = wrapRouteHandler(routeHandler, middleware);
4167
+ }
4168
+ return wrapped;
161
4169
  }
162
4170
 
163
4171
  // ../../src/config/rateLimit.ts
@@ -186,79 +4194,16 @@ function resolveLoginRateLimit() {
186
4194
  decaySeconds: parsePositiveInt(process.env.LOGIN_RATE_LIMIT_WINDOW_SECONDS, defaults.decaySeconds)
187
4195
  };
188
4196
  }
189
-
190
- // ../../src/core/auth/membershipContext.ts
191
- import { AsyncLocalStorage as AsyncLocalStorage3 } from "async_hooks";
192
-
193
- // ../../src/config/database.ts
194
- function readInteger(name, fallback) {
195
- const parsed = Number.parseInt(process.env[name] ?? String(fallback), 10);
196
- return Number.isInteger(parsed) && parsed >= 0 ? parsed : fallback;
197
- }
198
- var databaseConfig = {
199
- url: process.env.DATABASE_URL ?? "",
200
- poolMax: readInteger("DB_POOL_MAX", 10),
201
- idleTimeoutSeconds: readInteger("DB_POOL_IDLE_TIMEOUT", 30),
202
- maxLifetimeSeconds: readInteger("DB_POOL_MAX_LIFETIME", 3600),
203
- connectionTimeoutSeconds: readInteger("DB_CONNECTION_TIMEOUT", 10)
204
- };
205
-
206
- // ../../src/core/database/connectionContext.ts
207
- import { AsyncLocalStorage } from "async_hooks";
208
- var activeConnection = new AsyncLocalStorage;
209
- function runWithDatabaseConnection(connection, callback) {
210
- return activeConnection.run(connection, callback);
211
- }
212
- function getActiveDatabaseConnection(fallback) {
213
- return activeConnection.getStore() ?? fallback;
214
- }
215
-
216
- // ../../src/db/connection/createConnection.ts
217
- var {SQL } = globalThis.Bun;
218
- function createDatabaseConnection(config) {
219
- if (!config.url) {
220
- throw new Error("DATABASE_URL is not configured. Set DATABASE_URL before starting the app or running integration tests.");
221
- }
222
- return new SQL({
223
- url: config.url,
224
- max: config.poolMax,
225
- idleTimeout: config.idleTimeoutSeconds,
226
- maxLifetime: config.maxLifetimeSeconds,
227
- connectionTimeout: config.connectionTimeoutSeconds
228
- });
4197
+ function resolveRegisterRateLimit() {
4198
+ const defaults = isLocalAppEnv() ? { maxAttempts: 100, decaySeconds: 60 } : { maxAttempts: 10, decaySeconds: 60 };
4199
+ return {
4200
+ maxAttempts: parsePositiveInt(process.env.REGISTER_RATE_LIMIT_PER_WINDOW, defaults.maxAttempts),
4201
+ decaySeconds: parsePositiveInt(process.env.REGISTER_RATE_LIMIT_WINDOW_SECONDS ?? process.env.REGISTER_RATE_LIMIT_WINDOW_MS ? String(Number(process.env.REGISTER_RATE_LIMIT_WINDOW_MS) / 1000) : undefined, defaults.decaySeconds)
4202
+ };
229
4203
  }
230
4204
 
231
- // ../../src/db/connection/index.ts
232
- var connectionHolder = {
233
- connection: null
234
- };
235
- function getDatabase() {
236
- if (!connectionHolder.connection) {
237
- connectionHolder.connection = createDatabaseConnection(databaseConfig);
238
- }
239
- return connectionHolder.connection;
240
- }
241
- var POOL_CONNECTION_METHODS = new Set(["begin", "close", "connect"]);
242
- function resolveDatabase() {
243
- return getActiveDatabaseConnection(getDatabase());
244
- }
245
- function resolveDatabaseForProperty(property) {
246
- if (typeof property === "string" && POOL_CONNECTION_METHODS.has(property)) {
247
- return getDatabase();
248
- }
249
- return resolveDatabase();
250
- }
251
- var db = new Proxy(function database() {}, {
252
- apply(_target, _thisArg, args) {
253
- return resolveDatabase()(...args);
254
- },
255
- get(_target, property) {
256
- const connection = resolveDatabaseForProperty(property);
257
- const value = connection[property];
258
- return typeof value === "function" ? value.bind(connection) : value;
259
- }
260
- });
261
- var connection_default = db;
4205
+ // ../../src/core/auth/membershipContext.ts
4206
+ import { AsyncLocalStorage as AsyncLocalStorage4 } from "async_hooks";
262
4207
 
263
4208
  // ../../src/modules/organization/memberRepository.ts
264
4209
  class OrganizationMemberRepository {
@@ -311,45 +4256,6 @@ class OrganizationMemberRepository {
311
4256
  }
312
4257
  var memberRepository_default = OrganizationMemberRepository;
313
4258
 
314
- // ../../src/core/errors/http.ts
315
- class HttpError extends Error {
316
- status;
317
- details;
318
- constructor(status, message, details) {
319
- super(message);
320
- this.name = new.target.name;
321
- this.status = status;
322
- this.details = details;
323
- }
324
- }
325
- class ForbiddenError extends HttpError {
326
- constructor(message = "Forbidden", details) {
327
- super(403, message, details);
328
- }
329
- }
330
-
331
- class UnauthorizedError extends HttpError {
332
- constructor(message = "Unauthorized", details) {
333
- super(401, message, details);
334
- }
335
- }
336
-
337
- class PayloadTooLargeError extends HttpError {
338
- constructor(message = "Payload Too Large", details) {
339
- super(413, message, details);
340
- }
341
- }
342
-
343
- // ../../src/core/auth/authContext.ts
344
- import { AsyncLocalStorage as AsyncLocalStorage2 } from "async_hooks";
345
- var authContext = new AsyncLocalStorage2;
346
- function runWithAuthUser(user, callback) {
347
- return authContext.run(user, callback);
348
- }
349
- function currentAuthUser() {
350
- return authContext.getStore() ?? null;
351
- }
352
-
353
4259
  // ../../src/core/auth/accessControl.ts
354
4260
  function isGlobalAdmin(user) {
355
4261
  return user?.role === "admin";
@@ -363,7 +4269,7 @@ function resolveUserId(user) {
363
4269
  }
364
4270
 
365
4271
  // ../../src/core/auth/membershipContext.ts
366
- var membershipContext = new AsyncLocalStorage3;
4272
+ var membershipContext = new AsyncLocalStorage4;
367
4273
  var membershipRepository = new memberRepository_default;
368
4274
  async function runWithMembershipContext(callback) {
369
4275
  const user = currentAuthUser();
@@ -462,173 +4368,42 @@ var corsConfig = {
462
4368
  "X-Authenticated-User-Role",
463
4369
  "If-Match",
464
4370
  "If-None-Match"
465
- ],
466
- maxAgeSeconds: 86400
467
- };
468
-
469
- // ../../src/core/http/corsMiddleware.ts
470
- function createCorsMiddleware() {
471
- return async (request, next) => {
472
- if (request.method === "OPTIONS") {
473
- return new Response(null, {
474
- status: 204,
475
- headers: buildCorsHeaders(request)
476
- });
477
- }
478
- const response = await next();
479
- const headers = new Headers(response.headers);
480
- for (const [key, value] of buildCorsHeaders(request)) {
481
- headers.set(key, value);
482
- }
483
- return new Response(response.body, {
484
- status: response.status,
485
- statusText: response.statusText,
486
- headers
487
- });
488
- };
489
- }
490
- function buildCorsHeaders(request) {
491
- const headers = new Headers;
492
- const origin = request.headers.get("origin");
493
- const allowedOrigins = corsConfig.allowedOrigins;
494
- const allowOrigin = allowedOrigins.includes("*") || origin && allowedOrigins.includes(origin) ? origin ?? "*" : allowedOrigins[0] ?? "*";
495
- headers.set("Access-Control-Allow-Origin", allowOrigin);
496
- headers.set("Access-Control-Allow-Methods", corsConfig.allowedMethods.join(", "));
497
- headers.set("Access-Control-Allow-Headers", corsConfig.allowedHeaders.join(", "));
498
- headers.set("Access-Control-Max-Age", String(corsConfig.maxAgeSeconds));
499
- headers.set("Vary", "Origin");
500
- return headers;
501
- }
502
-
503
- // ../../src/core/http/csrfToken.ts
504
- import { createHmac, randomBytes, timingSafeEqual } from "crypto";
505
-
506
- // ../../src/core/http/requestMetaContext.ts
507
- import { AsyncLocalStorage as AsyncLocalStorage4 } from "async_hooks";
508
- var requestMetaContext = new AsyncLocalStorage4;
509
- function runWithRequestMeta(meta, callback) {
510
- return requestMetaContext.run(meta, callback);
511
- }
512
- function currentRequestMeta() {
513
- return requestMetaContext.getStore() ?? {
514
- ipAddress: null,
515
- userAgent: null
516
- };
517
- }
518
-
519
- // ../../src/core/http/csrfToken.ts
520
- var CSRF_COOKIE = "workhub_csrf";
521
- var CSRF_TTL_MS = 60 * 60 * 1000;
522
- function resolveCsrfSecret() {
523
- return process.env.SESSION_SECRET?.trim() || process.env.OAUTH_STATE_SECRET?.trim() || process.env.ADMIN_API_TOKEN?.trim() || "workhub-dev-csrf-secret";
524
- }
525
- function signCsrfToken(token, issuedAt) {
526
- const payload = `${token}.${issuedAt}`;
527
- const signature = createHmac("sha256", resolveCsrfSecret()).update(payload).digest("hex");
528
- return `${payload}.${signature}`;
529
- }
530
- function readCsrfCookie(request) {
531
- const cookieHeader = request.headers.get("cookie");
532
- if (!cookieHeader) {
533
- return null;
534
- }
535
- for (const part of cookieHeader.split(";")) {
536
- const [name, ...rest] = part.trim().split("=");
537
- if (name === CSRF_COOKIE) {
538
- return decodeURIComponent(rest.join("="));
539
- }
540
- }
541
- return null;
542
- }
543
- function parseSignedCsrfValue(cookieValue) {
544
- const parts = cookieValue.split(".");
545
- if (parts.length !== 3) {
546
- return null;
547
- }
548
- const [token, issuedAtRaw, cookieSignature] = parts;
549
- if (!token || !issuedAtRaw || !cookieSignature) {
550
- return null;
551
- }
552
- const issuedAt = Number.parseInt(issuedAtRaw, 10);
553
- if (!Number.isFinite(issuedAt)) {
554
- return null;
555
- }
556
- if (Date.now() - issuedAt > CSRF_TTL_MS) {
557
- return null;
558
- }
559
- const expectedSignature = signCsrfToken(token, issuedAt).split(".").pop();
560
- if (!expectedSignature) {
561
- return null;
562
- }
563
- const expectedBuffer = Buffer.from(expectedSignature);
564
- const actualBuffer = Buffer.from(cookieSignature);
565
- if (expectedBuffer.length !== actualBuffer.length) {
566
- return null;
567
- }
568
- if (!timingSafeEqual(expectedBuffer, actualBuffer)) {
569
- return null;
570
- }
571
- return { token, issuedAt };
572
- }
573
- function createCsrfTokenCookie() {
574
- const token = randomBytes(24).toString("hex");
575
- const issuedAt = Date.now();
576
- const value = signCsrfToken(token, issuedAt);
577
- return {
578
- token,
579
- cookie: `${CSRF_COOKIE}=${encodeURIComponent(value)}; Path=/; SameSite=Lax; Max-Age=3600`
580
- };
581
- }
582
- function resolveCsrfToken(request) {
583
- const cookieValue = readCsrfCookie(request);
584
- if (cookieValue) {
585
- const parsed = parseSignedCsrfValue(cookieValue);
586
- if (parsed) {
587
- return { token: parsed.token };
4371
+ ],
4372
+ maxAgeSeconds: 86400
4373
+ };
4374
+
4375
+ // ../../src/core/http/corsMiddleware.ts
4376
+ function createCorsMiddleware() {
4377
+ return async (request, next) => {
4378
+ if (request.method === "OPTIONS") {
4379
+ return new Response(null, {
4380
+ status: 204,
4381
+ headers: buildCorsHeaders(request)
4382
+ });
588
4383
  }
589
- }
590
- return createCsrfTokenCookie();
591
- }
592
- function readSubmittedCsrfToken(request) {
593
- const headerToken = request.headers.get("x-csrf-token")?.trim();
594
- if (headerToken) {
595
- return headerToken;
596
- }
597
- return null;
598
- }
599
- async function readSubmittedCsrfTokenFromBody(request) {
600
- const headerToken = readSubmittedCsrfToken(request);
601
- if (headerToken) {
602
- return headerToken;
603
- }
604
- const contentType = request.headers.get("content-type")?.toLowerCase() ?? "";
605
- if (contentType.includes("application/x-www-form-urlencoded") || contentType.includes("multipart/form-data")) {
606
- const formData = await request.clone().formData();
607
- const field = formData.get("_token");
608
- if (typeof field === "string" && field.trim().length > 0) {
609
- return field.trim();
4384
+ const response = await next();
4385
+ const headers = new Headers(response.headers);
4386
+ for (const [key, value] of buildCorsHeaders(request)) {
4387
+ headers.set(key, value);
610
4388
  }
611
- }
612
- return null;
4389
+ return new Response(response.body, {
4390
+ status: response.status,
4391
+ statusText: response.statusText,
4392
+ headers
4393
+ });
4394
+ };
613
4395
  }
614
- function verifyCsrfToken(request, submittedToken) {
615
- if (!submittedToken) {
616
- return false;
617
- }
618
- const cookieValue = readCsrfCookie(request);
619
- if (!cookieValue) {
620
- return false;
621
- }
622
- const parsed = parseSignedCsrfValue(cookieValue);
623
- if (!parsed) {
624
- return false;
625
- }
626
- const submittedBuffer = Buffer.from(submittedToken);
627
- const expectedBuffer = Buffer.from(parsed.token);
628
- if (submittedBuffer.length !== expectedBuffer.length) {
629
- return false;
630
- }
631
- return timingSafeEqual(submittedBuffer, expectedBuffer);
4396
+ function buildCorsHeaders(request) {
4397
+ const headers = new Headers;
4398
+ const origin = request.headers.get("origin");
4399
+ const allowedOrigins = corsConfig.allowedOrigins;
4400
+ const allowOrigin = allowedOrigins.includes("*") || origin && allowedOrigins.includes(origin) ? origin ?? "*" : allowedOrigins[0] ?? "*";
4401
+ headers.set("Access-Control-Allow-Origin", allowOrigin);
4402
+ headers.set("Access-Control-Allow-Methods", corsConfig.allowedMethods.join(", "));
4403
+ headers.set("Access-Control-Allow-Headers", corsConfig.allowedHeaders.join(", "));
4404
+ headers.set("Access-Control-Max-Age", String(corsConfig.maxAgeSeconds));
4405
+ headers.set("Vary", "Origin");
4406
+ return headers;
632
4407
  }
633
4408
 
634
4409
  // ../../src/core/http/csrfMiddleware.ts
@@ -663,90 +4438,6 @@ function createCsrfMiddleware() {
663
4438
  };
664
4439
  }
665
4440
 
666
- // ../../src/core/http/flashSession.ts
667
- import { createHmac as createHmac2, timingSafeEqual as timingSafeEqual2 } from "crypto";
668
- var FLASH_COOKIE = "workhub_flash";
669
- var FLASH_TTL_MS = 60 * 1000;
670
- function resolveFlashSecret() {
671
- return process.env.SESSION_SECRET?.trim() || process.env.OAUTH_STATE_SECRET?.trim() || "workhub-dev-flash-secret";
672
- }
673
- function signFlashPayload(payload, issuedAt) {
674
- const signature = createHmac2("sha256", resolveFlashSecret()).update(`${payload}.${issuedAt}`).digest("hex");
675
- return `${payload}.${issuedAt}.${signature}`;
676
- }
677
- function readFlashCookie(request) {
678
- const cookieHeader = request.headers.get("cookie");
679
- if (!cookieHeader) {
680
- return null;
681
- }
682
- for (const part of cookieHeader.split(";")) {
683
- const [name, ...rest] = part.trim().split("=");
684
- if (name === FLASH_COOKIE) {
685
- return decodeURIComponent(rest.join("="));
686
- }
687
- }
688
- return null;
689
- }
690
- function parseFlashCookie(cookieValue) {
691
- const parts = cookieValue.split(".");
692
- if (parts.length < 3) {
693
- return null;
694
- }
695
- const signature = parts.pop();
696
- const issuedAtRaw = parts.pop();
697
- const payload = parts.join(".");
698
- if (!signature || !issuedAtRaw || !payload) {
699
- return null;
700
- }
701
- const issuedAt = Number.parseInt(issuedAtRaw, 10);
702
- if (!Number.isFinite(issuedAt) || Date.now() - issuedAt > FLASH_TTL_MS) {
703
- return null;
704
- }
705
- const expectedSignature = signFlashPayload(payload, issuedAt).split(".").pop();
706
- if (!expectedSignature) {
707
- return null;
708
- }
709
- const expectedBuffer = Buffer.from(expectedSignature);
710
- const actualBuffer = Buffer.from(signature);
711
- if (expectedBuffer.length !== actualBuffer.length) {
712
- return null;
713
- }
714
- if (!timingSafeEqual2(expectedBuffer, actualBuffer)) {
715
- return null;
716
- }
717
- try {
718
- const parsed = JSON.parse(Buffer.from(payload, "base64url").toString("utf8"));
719
- if (!parsed?.message || typeof parsed.message !== "string") {
720
- return null;
721
- }
722
- if (parsed.level !== "success" && parsed.level !== "error" && parsed.level !== "info") {
723
- return null;
724
- }
725
- return parsed;
726
- } catch {
727
- return null;
728
- }
729
- }
730
- function clearFlashCookie() {
731
- return `${FLASH_COOKIE}=; Path=/; HttpOnly; SameSite=Lax; Max-Age=0`;
732
- }
733
- function pullFlash(request) {
734
- const cookieValue = readFlashCookie(request);
735
- if (!cookieValue) {
736
- return null;
737
- }
738
- return parseFlashCookie(cookieValue);
739
- }
740
- function withFlashClear(response) {
741
- const headers = new Headers(response.headers);
742
- headers.append("set-cookie", clearFlashCookie());
743
- return new Response(response.body, {
744
- status: response.status,
745
- statusText: response.statusText,
746
- headers
747
- });
748
- }
749
-
750
4441
  // ../../src/core/http/flashMiddleware.ts
751
4442
  function createFlashMiddleware() {
752
4443
  return async (request, next) => {
@@ -763,7 +4454,7 @@ function createFlashMiddleware() {
763
4454
  }
764
4455
 
765
4456
  // ../../src/core/http/loginThrottleMiddleware.ts
766
- var {RedisClient } = globalThis.Bun;
4457
+ var {RedisClient: RedisClient3 } = globalThis.Bun;
767
4458
  function resolveLoginIdentity(request) {
768
4459
  return request.headers.get("x-forwarded-for")?.split(",")[0]?.trim() ?? "unknown";
769
4460
  }
@@ -782,7 +4473,7 @@ async function resolveLoginEmail(request) {
782
4473
  }
783
4474
  }
784
4475
  function createLoginThrottleMiddleware(options) {
785
- const client = new RedisClient(options.redisUrl);
4476
+ const client = new RedisClient3(options.redisUrl);
786
4477
  const prefix = options.keyPrefix ?? "workhub:login-throttle:";
787
4478
  return async (request, next) => {
788
4479
  const identity = resolveLoginIdentity(request);
@@ -918,38 +4609,6 @@ function createMetricsMiddleware() {
918
4609
  };
919
4610
  }
920
4611
 
921
- // ../../src/core/http/middleware.ts
922
- function composeMiddleware(...middleware) {
923
- return (handler) => {
924
- return async (request) => {
925
- let index = 0;
926
- const dispatch = async () => {
927
- if (index >= middleware.length) {
928
- return await handler(request);
929
- }
930
- const current = middleware[index];
931
- index += 1;
932
- if (!current) {
933
- return await handler(request);
934
- }
935
- return await current(request, dispatch);
936
- };
937
- return await dispatch();
938
- };
939
- };
940
- }
941
- async function requestIdMiddleware(request, next) {
942
- const requestId = request.headers.get("x-request-id") ?? crypto.randomUUID();
943
- const response = await next();
944
- const headers = new Headers(response.headers);
945
- headers.set("x-request-id", requestId);
946
- return new Response(response.body, {
947
- status: response.status,
948
- statusText: response.statusText,
949
- headers
950
- });
951
- }
952
-
953
4612
  // ../../src/core/http/requireAbilityMiddleware.ts
954
4613
  function createRequireAbilityMiddleware(abilityChecker) {
955
4614
  return (ability) => {
@@ -980,7 +4639,7 @@ function createRequireAuthMiddleware(auth) {
980
4639
  }
981
4640
 
982
4641
  // ../../src/core/security/securityEvents.ts
983
- function logSecurityEvent(event, details = {}) {
4642
+ function logSecurityEvent2(event, details = {}) {
984
4643
  const meta = currentRequestMeta();
985
4644
  const user = currentAuthUser();
986
4645
  console.log(JSON.stringify({
@@ -999,7 +4658,7 @@ function createRequireGlobalAdminMiddleware() {
999
4658
  return async (_request, next) => {
1000
4659
  const user = currentAuthUser();
1001
4660
  if (!isGlobalAdmin(user)) {
1002
- logSecurityEvent("privilege_escalation_blocked", {
4661
+ logSecurityEvent2("privilege_escalation_blocked", {
1003
4662
  required_role: "platform_admin",
1004
4663
  path: new URL(_request.url).pathname
1005
4664
  });
@@ -1056,15 +4715,6 @@ function withMiddleware(...middleware) {
1056
4715
  };
1057
4716
  }
1058
4717
 
1059
- // ../../src/config/app.ts
1060
- var appConfig = {
1061
- name: "WorkHub",
1062
- env: process.env.APP_ENV ?? "local",
1063
- debug: (process.env.APP_DEBUG ?? "true") !== "false",
1064
- url: process.env.APP_URL ?? "http://localhost:3000",
1065
- apiPrefix: process.env.API_PREFIX ?? "/api/v1"
1066
- };
1067
-
1068
4718
  // ../../src/config/contentSecurityPolicy.ts
1069
4719
  function strictApiContentSecurityPolicy() {
1070
4720
  return "default-src 'none'; frame-ancestors 'none'; base-uri 'none'";
@@ -1131,7 +4781,7 @@ function createSecurityHeadersMiddleware() {
1131
4781
  }
1132
4782
 
1133
4783
  // ../../src/core/http/throttleMiddleware.ts
1134
- var {RedisClient: RedisClient2 } = globalThis.Bun;
4784
+ var {RedisClient: RedisClient4 } = globalThis.Bun;
1135
4785
 
1136
4786
  // ../../src/core/tenant/tenantContext.ts
1137
4787
  import { AsyncLocalStorage as AsyncLocalStorage5 } from "async_hooks";
@@ -1165,7 +4815,7 @@ function resolveThrottleIdentity(request) {
1165
4815
  return request.headers.get("x-forwarded-for")?.split(",")[0]?.trim() ?? "unknown";
1166
4816
  }
1167
4817
  function createThrottleMiddleware(options) {
1168
- const client = new RedisClient2(options.redisUrl);
4818
+ const client = new RedisClient4(options.redisUrl);
1169
4819
  const prefix = options.keyPrefix ?? "workhub:throttle:";
1170
4820
  return async (request, next) => {
1171
4821
  const identity = resolveThrottleIdentity(request);
@@ -1212,42 +4862,11 @@ function createRequestLoggingMiddleware() {
1212
4862
  };
1213
4863
  }
1214
4864
 
1215
- // ../../src/config/features.ts
1216
- function readFeatureFlags() {
1217
- return {
1218
- webhooks: (process.env.FEATURE_WEBHOOKS ?? "true") !== "false",
1219
- fullTextSearch: (process.env.FEATURE_SEARCH ?? "true") !== "false",
1220
- auditLog: (process.env.FEATURE_AUDIT_LOG ?? "true") !== "false",
1221
- oauthLogin: (process.env.FEATURE_OAUTH ?? "true") !== "false",
1222
- samlLogin: (process.env.FEATURE_SAML ?? "false") === "true",
1223
- scim: (process.env.FEATURE_SCIM ?? "true") !== "false",
1224
- billing: (process.env.FEATURE_BILLING ?? "true") !== "false",
1225
- siemExport: (process.env.FEATURE_SIEM_EXPORT ?? "true") !== "false",
1226
- publicReads: (process.env.FEATURE_PUBLIC_READS ?? "true") !== "false",
1227
- emailVerification: (process.env.FEATURE_EMAIL_VERIFICATION ?? "false") === "true",
1228
- mfa: (process.env.FEATURE_MFA ?? "false") === "true"
1229
- };
1230
- }
1231
- var featureFlags = readFeatureFlags();
1232
- function isFeatureEnabled(feature) {
1233
- return readFeatureFlags()[feature];
1234
- }
1235
-
1236
4865
  // ../../src/core/security/publicReads.ts
1237
4866
  function isPublicReadsEnabled() {
1238
4867
  return isFeatureEnabled("publicReads");
1239
4868
  }
1240
4869
 
1241
- // ../../src/core/tenant/databaseTenantContext.ts
1242
- async function runWithMigrationBypass(callback) {
1243
- await connection_default`SELECT set_config('app.bypass_rls', 'true', false)`;
1244
- try {
1245
- return await callback();
1246
- } finally {
1247
- await connection_default`SELECT set_config('app.bypass_rls', 'false', false)`;
1248
- }
1249
- }
1250
-
1251
4870
  // ../../src/core/tenant/resolveTenant.ts
1252
4871
  async function resolveTenant(tenantId) {
1253
4872
  const rows = await connection_default`
@@ -1543,29 +5162,41 @@ class HttpKernel {
1543
5162
  return withMiddleware(createAuthorizeMiddleware(gate, auth, resource, action))(handler);
1544
5163
  }
1545
5164
  wrapLogin(handler) {
5165
+ return this.wrapThrottle("login", resolveLoginRateLimit(), handler);
5166
+ }
5167
+ wrapRegister(handler) {
5168
+ return this.wrapThrottle("register", resolveRegisterRateLimit(), handler);
5169
+ }
5170
+ wrapThrottle(scope, rateLimit, handler) {
1546
5171
  const middleware = [];
1547
- const loginRateLimit = resolveLoginRateLimit();
5172
+ const memoryKeyPrefix = scope === "login" ? "login-throttle:" : "register-throttle:";
1548
5173
  if (this.dependencies.container.has(CORE_CONFIG_TOKEN)) {
1549
5174
  const config = this.dependencies.container.resolve(CORE_CONFIG_TOKEN);
1550
5175
  const redisUrl = config.get(REDIS_URL_CONFIG_KEY)?.trim() ?? "";
1551
5176
  if (redisUrl) {
1552
- middleware.push(createLoginThrottleMiddleware({
5177
+ const throttle = scope === "login" ? createLoginThrottleMiddleware({
1553
5178
  redisUrl,
1554
- maxAttempts: loginRateLimit.maxAttempts,
1555
- decaySeconds: loginRateLimit.decaySeconds
1556
- }));
5179
+ maxAttempts: rateLimit.maxAttempts,
5180
+ decaySeconds: rateLimit.decaySeconds
5181
+ }) : createThrottleMiddleware({
5182
+ redisUrl,
5183
+ maxAttempts: rateLimit.maxAttempts,
5184
+ decaySeconds: rateLimit.decaySeconds,
5185
+ keyPrefix: memoryKeyPrefix
5186
+ });
5187
+ middleware.push(throttle);
1557
5188
  } else {
1558
5189
  middleware.push(createMemoryThrottleMiddleware({
1559
- maxAttempts: loginRateLimit.maxAttempts,
1560
- decaySeconds: loginRateLimit.decaySeconds,
1561
- keyPrefix: "workhub:login-throttle:"
5190
+ maxAttempts: rateLimit.maxAttempts,
5191
+ decaySeconds: rateLimit.decaySeconds,
5192
+ keyPrefix: memoryKeyPrefix
1562
5193
  }));
1563
5194
  }
1564
5195
  } else {
1565
5196
  middleware.push(createMemoryThrottleMiddleware({
1566
- maxAttempts: loginRateLimit.maxAttempts,
1567
- decaySeconds: loginRateLimit.decaySeconds,
1568
- keyPrefix: "workhub:login-throttle:"
5197
+ maxAttempts: rateLimit.maxAttempts,
5198
+ decaySeconds: rateLimit.decaySeconds,
5199
+ keyPrefix: memoryKeyPrefix
1569
5200
  }));
1570
5201
  }
1571
5202
  if (middleware.length === 0) {
@@ -1577,6 +5208,82 @@ class HttpKernel {
1577
5208
  function createHttpKernel(dependencies) {
1578
5209
  return new HttpKernel(dependencies);
1579
5210
  }
5211
+
5212
+ // ../../src/bootstrap/routeRegistry.ts
5213
+ class RouteRegistry {
5214
+ routes = [];
5215
+ register(route) {
5216
+ this.routes.push(route);
5217
+ }
5218
+ clear() {
5219
+ this.routes.length = 0;
5220
+ }
5221
+ list() {
5222
+ return [...this.routes].sort((left, right) => left.path.localeCompare(right.path));
5223
+ }
5224
+ }
5225
+ var routeRegistry = new RouteRegistry;
5226
+
5227
+ // ../../src/bootstrap/createWebRoutes.ts
5228
+ function registerRoute(method, path, middleware) {
5229
+ routeRegistry.register({ method, path, middleware });
5230
+ }
5231
+ function registerRouteMap(routes, middleware) {
5232
+ const registered = {};
5233
+ for (const [path, handler] of Object.entries(routes)) {
5234
+ if (handler && typeof handler === "object" && !Array.isArray(handler)) {
5235
+ const methodMap = handler;
5236
+ registered[path] = methodMap;
5237
+ for (const method of Object.keys(methodMap)) {
5238
+ registerRoute(method.toUpperCase(), path, middleware);
5239
+ }
5240
+ continue;
5241
+ }
5242
+ registered[path] = handler;
5243
+ registerRoute("GET", path, middleware);
5244
+ }
5245
+ return registered;
5246
+ }
5247
+ function createWebRoutes(dependencies) {
5248
+ const kernel = createHttpKernel(dependencies);
5249
+ const middleware = [...kernel.globalMiddleware(), ...kernel.group("web")];
5250
+ const moduleRoutes = {
5251
+ "/": () => Response.redirect("/organizations", 302)
5252
+ };
5253
+ registerRoute("GET", "/", ["global", "web"]);
5254
+ for (const module of appModules) {
5255
+ if (!module.webRoutes) {
5256
+ continue;
5257
+ }
5258
+ Object.assign(moduleRoutes, module.webRoutes({
5259
+ dependencies,
5260
+ cachedJson: async () => htmlResponse(""),
5261
+ kernel
5262
+ }));
5263
+ }
5264
+ const wrappedRoutes = applyMiddlewareToRoutes(registerRouteMap(moduleRoutes, ["global", "web"]), middleware);
5265
+ wrappedRoutes["/assets/*"] = async (request) => {
5266
+ registerRoute("GET", "/assets/*", ["global", "web"]);
5267
+ const pathname = new URL(request.url).pathname;
5268
+ const relativePath = pathname.replace(/^\//, "");
5269
+ const file = Bun.file(join4(process.cwd(), "public", relativePath));
5270
+ if (!await file.exists()) {
5271
+ return htmlResponse("Not Found", { status: 404 });
5272
+ }
5273
+ return new Response(file);
5274
+ };
5275
+ registerRoute("GET", "/assets/*", ["global", "web"]);
5276
+ return wrappedRoutes;
5277
+ }
5278
+ function mergeWebRoutes(dependencies, routes) {
5279
+ if (!isViewsEnabled()) {
5280
+ return routes;
5281
+ }
5282
+ return {
5283
+ ...createWebRoutes(dependencies),
5284
+ ...routes
5285
+ };
5286
+ }
1580
5287
  // ../../src/bootstrap/prefixRouteMap.ts
1581
5288
  function prefixRouteMap(prefix, routes) {
1582
5289
  const normalizedPrefix = prefix.replace(/\/$/, "");
@@ -1738,16 +5445,26 @@ function slugify(value) {
1738
5445
  export {
1739
5446
  slugify,
1740
5447
  setActiveApplicationContext,
5448
+ scheduleRunCommand,
5449
+ runProviderPhase,
5450
+ runDueScheduledTasks,
1741
5451
  resolveService,
1742
5452
  resolveApplicationQueue,
1743
5453
  prefixRouteMap,
1744
5454
  parseFormBody,
5455
+ mergeWebRoutes,
1745
5456
  getRequiredDependency,
1746
5457
  createWebServer,
5458
+ createWebRoutes,
1747
5459
  createHttpKernel,
1748
5460
  createCsrfProtection,
5461
+ createAppContext,
5462
+ coreProviders,
5463
+ collectProviders,
1749
5464
  assertAppDependenciesComplete,
5465
+ appSchedule,
1750
5466
  ServiceContainer,
5467
+ Schedule,
1751
5468
  REDIS_URL_CONFIG_KEY,
1752
5469
  DEFAULT_APP_PORT,
1753
5470
  DATABASE_URL_CONFIG_KEY,