@getstrata/bootstrap 0.2.26 → 0.2.29

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 (36) hide show
  1. package/dist/bootstrap/http/securedRouteModelBinding.d.ts +2 -2
  2. package/dist/bootstrap/listeners/invalidateCacheOnModelWrite.d.ts +1 -1
  3. package/dist/bootstrap/schedule.d.ts +2 -1
  4. package/dist/bootstrap/web/forms.d.ts +1 -1
  5. package/dist/entries/applicationRegistry.js +2 -0
  6. package/dist/entries/buildModuleRoutes.js +5 -0
  7. package/dist/entries/buildWebModuleRoutes.js +5 -0
  8. package/dist/entries/cache/modelCacheTags.js +2 -0
  9. package/dist/entries/config.js +2 -0
  10. package/dist/entries/context.js +99 -3156
  11. package/dist/entries/contracts.js +2 -0
  12. package/dist/entries/createRoutes.js +1468 -0
  13. package/dist/entries/createSpaRoutes.js +64 -0
  14. package/dist/entries/createWebRoutes.js +5 -0
  15. package/dist/entries/dependencies.js +99 -3156
  16. package/dist/entries/discoverModules.js +2 -0
  17. package/dist/entries/health.js +215 -0
  18. package/dist/entries/http/securedRouteModelBinding.js +6 -293
  19. package/dist/entries/httpKernel.js +5 -0
  20. package/dist/entries/listeners/invalidateCacheOnModelWrite.js +120 -0
  21. package/dist/entries/membershipService.js +2 -0
  22. package/dist/entries/metricsRoutes.js +18 -0
  23. package/dist/entries/providers/view.js +8 -603
  24. package/dist/entries/providers.js +94 -3158
  25. package/dist/entries/queue/defaultJobs.js +7 -465
  26. package/dist/entries/routeRegistry.js +2 -0
  27. package/dist/entries/schedule.js +49 -0
  28. package/dist/entries/secretsGuard.js +9 -0
  29. package/dist/entries/web/forms.js +4 -18
  30. package/dist/entries/web/routing.js +21 -304
  31. package/dist/entries/web/server.js +2 -0
  32. package/dist/entries/web/session.js +3 -26
  33. package/dist/entries/web/slug.js +2 -0
  34. package/dist/index-sfreg6q3.js +0 -0
  35. package/dist/index.js +176 -3543
  36. package/package.json +32 -2
@@ -1,4 +1,6 @@
1
1
  // @bun
2
+ var __jsonParse = (a) => JSON.parse(a);
3
+
2
4
  // ../../src/bootstrap/applicationRegistry.ts
3
5
  import {
4
6
  resolveApplicationAuth,
@@ -82,6 +84,14 @@ async function ensureModulesLoaded(options) {
82
84
  function discoverModules() {
83
85
  return readDiscoverModulesState().appModules;
84
86
  }
87
+ // ../../src/bootstrap/providers/auth.ts
88
+ import {
89
+ AuthManager,
90
+ CompositeGuard,
91
+ DatabaseTokenGuard,
92
+ GuestGuard
93
+ } from "@getstrata/core/auth/guard";
94
+
85
95
  // ../../src/config/auth.ts
86
96
  var authConfig = {
87
97
  allowDevHeaders: (process.env.AUTH_DEV_HEADERS ?? "true") !== "false",
@@ -284,6 +294,25 @@ function getDb() {
284
294
  getDatabase();
285
295
  return getDefaultDatabaseQuery();
286
296
  }
297
+ async function pingDatabase(connection = getDatabase()) {
298
+ try {
299
+ await connection`SELECT 1`;
300
+ return true;
301
+ } catch {
302
+ return false;
303
+ }
304
+ }
305
+ async function ensureDatabaseConnection() {
306
+ if (await pingDatabase()) {
307
+ return getDatabase();
308
+ }
309
+ await getDatabase().close().catch(() => {
310
+ return;
311
+ });
312
+ connectionHolder.connection = createDatabaseConnection(databaseConfig);
313
+ registerDefaultDatabasePool(connectionHolder.connection);
314
+ return getDatabase();
315
+ }
287
316
  var db = new Proxy(function database() {}, {
288
317
  apply(_target, _thisArg, args) {
289
318
  return getDb()(...args);
@@ -294,6 +323,7 @@ var db = new Proxy(function database() {}, {
294
323
  return typeof value === "function" ? value.bind(connection) : value;
295
324
  }
296
325
  });
326
+ var connection_default = db;
297
327
 
298
328
  // ../../src/modules/user/apiTokenTable.ts
299
329
  import { defineTable } from "@getstrata/core/database";
@@ -474,145 +504,9 @@ import { ForbiddenError, NotFoundError as NotFoundError2 } from "@getstrata/core
474
504
  import { resolveDefaultTokenExpiryDays as resolveDefaultTokenExpiryDays2 } from "@getstrata/core/security/tokenExpiry";
475
505
 
476
506
  // ../../src/modules/user/provider.ts
507
+ var userRepositoryToken = "user.repository";
477
508
  var tokenServiceToken = CORE_TOKEN_SERVICE_TOKEN;
478
509
 
479
- // ../../src/core/errors/http.ts
480
- class HttpError extends Error {
481
- status;
482
- details;
483
- constructor(status, message, details) {
484
- super(message);
485
- this.name = new.target.name;
486
- this.status = status;
487
- this.details = details;
488
- }
489
- }
490
-
491
- class BadRequestError extends HttpError {
492
- constructor(message = "Bad Request", details) {
493
- super(400, message, details);
494
- }
495
- }
496
- class ConflictError extends HttpError {
497
- constructor(message = "Conflict", details) {
498
- super(409, message, details);
499
- }
500
- }
501
-
502
- class UnprocessableEntityError extends HttpError {
503
- constructor(message = "Unprocessable Entity", details) {
504
- super(422, message, details);
505
- }
506
- }
507
- class ForbiddenError2 extends HttpError {
508
- constructor(message = "Forbidden", details) {
509
- super(403, message, details);
510
- }
511
- }
512
-
513
- class UnauthorizedError2 extends HttpError {
514
- constructor(message = "Unauthorized", details) {
515
- super(401, message, details);
516
- }
517
- }
518
- class PreconditionFailedError extends HttpError {
519
- constructor(message = "Precondition Failed", details) {
520
- super(412, message, details);
521
- }
522
- }
523
-
524
- // ../../src/core/auth/authContext.ts
525
- var authContext = createAsyncContextStore("@getstrata/authContext");
526
- function currentAuthUser() {
527
- return authContext.getStore() ?? null;
528
- }
529
-
530
- // ../../src/core/auth/guard.ts
531
- function devHeaderAbilities(role) {
532
- if (role === "admin") {
533
- return [...ADMIN_ABILITIES];
534
- }
535
- return [...MEMBER_ABILITIES];
536
- }
537
-
538
- class GuestGuard {
539
- resolve(request) {
540
- const userId = request.headers.get("x-authenticated-user-id");
541
- if (!userId) {
542
- return null;
543
- }
544
- const role = request.headers.get("x-authenticated-user-role");
545
- return {
546
- id: userId,
547
- abilities: devHeaderAbilities(role),
548
- ...role ? { role } : {}
549
- };
550
- }
551
- }
552
- class DatabaseTokenGuard {
553
- container;
554
- constructor(container) {
555
- this.container = container;
556
- }
557
- async resolve(request) {
558
- const authorization = request.headers.get("authorization");
559
- if (!authorization?.startsWith("Bearer ")) {
560
- return null;
561
- }
562
- const token = authorization.slice("Bearer ".length).trim();
563
- if (!token) {
564
- return null;
565
- }
566
- if (!this.container.has(tokenServiceToken)) {
567
- return null;
568
- }
569
- const tokenService = this.container.resolve(tokenServiceToken);
570
- return await tokenService.resolveUserFromToken(token);
571
- }
572
- }
573
-
574
- class CompositeGuard {
575
- guards;
576
- constructor(guards) {
577
- this.guards = guards;
578
- }
579
- async resolve(request) {
580
- for (const guard of this.guards) {
581
- const user = await Promise.resolve(guard.resolve(request));
582
- if (user) {
583
- return user;
584
- }
585
- }
586
- return null;
587
- }
588
- }
589
-
590
- class AuthManager {
591
- guard;
592
- constructor(guard) {
593
- this.guard = guard;
594
- }
595
- async resolve(request) {
596
- if (request) {
597
- return await Promise.resolve(this.guard.resolve(request));
598
- }
599
- return currentAuthUser();
600
- }
601
- user(request) {
602
- return this.resolve(request);
603
- }
604
- async check(request) {
605
- return await this.user(request) !== null;
606
- }
607
- async requireUser(request) {
608
- const user = await this.user(request);
609
- if (!user) {
610
- throw new UnauthorizedError2;
611
- }
612
- return user;
613
- }
614
- }
615
-
616
510
  // ../../src/core/auth/sessionCookie.ts
617
511
  import { createHmac, timingSafeEqual } from "crypto";
618
512
  var SESSION_COOKIE = "workhub_session";
@@ -713,378 +607,8 @@ var authProvider = {
713
607
  };
714
608
  var auth_default = authProvider;
715
609
 
716
- // ../../src/core/cache/redisCacheStore.ts
717
- var {RedisClient } = globalThis.Bun;
718
- var KEY_PREFIX = "workhub:cache:";
719
- var TAG_PREFIX = "workhub:cache:tag:";
720
-
721
- class RedisCacheStore {
722
- ttlMs;
723
- maxEntries;
724
- client;
725
- inflight = new Map;
726
- keyTags = new Map;
727
- constructor(redisUrl, ttlMs, maxEntries) {
728
- this.ttlMs = ttlMs;
729
- this.maxEntries = maxEntries;
730
- this.client = new RedisClient(redisUrl);
731
- }
732
- async get(key) {
733
- const raw = await this.client.get(this.storageKey(key));
734
- if (raw === null) {
735
- return;
736
- }
737
- return JSON.parse(raw);
738
- }
739
- async set(key, value, ttlMs) {
740
- const resolvedTtlMs = ttlMs ?? this.ttlMs;
741
- const payload = JSON.stringify(value);
742
- if (resolvedTtlMs > 0) {
743
- await this.client.psetex(this.storageKey(key), resolvedTtlMs, payload);
744
- } else {
745
- await this.client.set(this.storageKey(key), payload);
746
- }
747
- await this.enforceMaxEntries();
748
- }
749
- async getOrSet(key, loader, ttlMs) {
750
- const cached = await this.get(key);
751
- if (cached !== undefined) {
752
- return cached;
753
- }
754
- const inflightRequest = this.inflight.get(key);
755
- if (inflightRequest) {
756
- return inflightRequest;
757
- }
758
- const pendingRequest = loader().then(async (value) => {
759
- await this.set(key, value, ttlMs);
760
- return value;
761
- }).finally(() => {
762
- this.inflight.delete(key);
763
- });
764
- this.inflight.set(key, pendingRequest);
765
- return pendingRequest;
766
- }
767
- async attachTags(key, tags) {
768
- if (tags.length === 0) {
769
- return;
770
- }
771
- let tagsForKey = this.keyTags.get(key);
772
- if (!tagsForKey) {
773
- tagsForKey = new Set;
774
- this.keyTags.set(key, tagsForKey);
775
- }
776
- for (const tag of tags) {
777
- tagsForKey.add(tag);
778
- await this.client.sadd(this.tagKey(tag), key);
779
- }
780
- }
781
- async flushTags(tags) {
782
- const keysToRemove = new Set;
783
- for (const tag of tags) {
784
- const members = await this.client.smembers(this.tagKey(tag));
785
- for (const member of members) {
786
- keysToRemove.add(member);
787
- }
788
- }
789
- let removed = 0;
790
- for (const key of keysToRemove) {
791
- if (await this.invalidate(key)) {
792
- removed += 1;
793
- }
794
- }
795
- for (const tag of tags) {
796
- await this.client.del(this.tagKey(tag));
797
- }
798
- return removed;
799
- }
800
- async invalidate(key) {
801
- const deleted = await this.client.del(this.storageKey(key));
802
- await this.detachKeyFromTags(key);
803
- return deleted > 0;
804
- }
805
- async invalidateByPrefix(prefix) {
806
- const keys = await this.client.keys(`${KEY_PREFIX}*`);
807
- let removed = 0;
808
- for (const storageKey of keys) {
809
- const key = storageKey.slice(KEY_PREFIX.length);
810
- if (key === prefix || key.startsWith(`${prefix}?`)) {
811
- if (await this.invalidate(key)) {
812
- removed += 1;
813
- }
814
- }
815
- }
816
- return removed;
817
- }
818
- async clear() {
819
- const keys = await this.client.keys(`${KEY_PREFIX}*`);
820
- if (keys.length > 0) {
821
- await this.client.del(...keys);
822
- }
823
- const tagKeys = await this.client.keys(`${TAG_PREFIX}*`);
824
- if (tagKeys.length > 0) {
825
- await this.client.del(...tagKeys);
826
- }
827
- this.inflight.clear();
828
- this.keyTags.clear();
829
- }
830
- async size() {
831
- const keys = await this.client.keys(`${KEY_PREFIX}*`);
832
- return keys.length;
833
- }
834
- storageKey(key) {
835
- return `${KEY_PREFIX}${key}`;
836
- }
837
- tagKey(tag) {
838
- return `${TAG_PREFIX}${tag}`;
839
- }
840
- async detachKeyFromTags(key) {
841
- const tags = this.keyTags.get(key);
842
- if (!tags) {
843
- return;
844
- }
845
- for (const tag of tags) {
846
- await this.client.srem(this.tagKey(tag), key);
847
- }
848
- this.keyTags.delete(key);
849
- }
850
- async enforceMaxEntries() {
851
- const keys = await this.client.keys(`${KEY_PREFIX}*`);
852
- if (keys.length <= this.maxEntries) {
853
- return;
854
- }
855
- const overflow = keys.length - this.maxEntries;
856
- const keysToRemove = keys.slice(0, overflow);
857
- if (keysToRemove.length > 0) {
858
- await this.client.del(...keysToRemove);
859
- }
860
- }
861
- }
862
- var redisCacheStore_default = RedisCacheStore;
863
-
864
- // ../../src/core/cache/simpleCache.ts
865
- class SimpleCache {
866
- ttlMs;
867
- maxEntries;
868
- cache = new Map;
869
- inflight = new Map;
870
- tagIndex = new Map;
871
- keyTags = new Map;
872
- constructor(ttlMs = 3600000, maxEntries = 100) {
873
- this.ttlMs = ttlMs;
874
- this.maxEntries = maxEntries;
875
- if (!Number.isFinite(ttlMs) || ttlMs < 0) {
876
- throw new RangeError("ttlMs must be a non-negative number.");
877
- }
878
- if (!Number.isInteger(maxEntries) || maxEntries < 1) {
879
- throw new RangeError("maxEntries must be a positive integer.");
880
- }
881
- }
882
- get(key) {
883
- return this.getFreshEntry(key)?.value;
884
- }
885
- set(key, value, ttlMs) {
886
- const now = Date.now();
887
- const resolvedTtlMs = ttlMs ?? this.ttlMs;
888
- this.cache.set(key, {
889
- value,
890
- expiresAt: now + resolvedTtlMs,
891
- lastAccessedAt: now
892
- });
893
- this.evictOverflow();
894
- }
895
- async getOrSet(key, loader, ttlMs) {
896
- this.pruneExpired();
897
- const cachedEntry = this.getFreshEntry(key);
898
- if (cachedEntry) {
899
- return cachedEntry.value;
900
- }
901
- const inflightRequest = this.inflight.get(key);
902
- if (inflightRequest) {
903
- return inflightRequest;
904
- }
905
- const pendingRequest = loader().then((value) => {
906
- this.set(key, value, ttlMs);
907
- return value;
908
- }).finally(() => {
909
- this.inflight.delete(key);
910
- });
911
- this.inflight.set(key, pendingRequest);
912
- return pendingRequest;
913
- }
914
- attachTags(key, tags) {
915
- if (tags.length === 0) {
916
- return;
917
- }
918
- let tagsForKey = this.keyTags.get(key);
919
- if (!tagsForKey) {
920
- tagsForKey = new Set;
921
- this.keyTags.set(key, tagsForKey);
922
- }
923
- for (const tag of tags) {
924
- tagsForKey.add(tag);
925
- let keysForTag = this.tagIndex.get(tag);
926
- if (!keysForTag) {
927
- keysForTag = new Set;
928
- this.tagIndex.set(tag, keysForTag);
929
- }
930
- keysForTag.add(key);
931
- }
932
- }
933
- flushTags(tags) {
934
- const keysToRemove = new Set;
935
- for (const tag of tags) {
936
- const keys = this.tagIndex.get(tag);
937
- if (!keys) {
938
- continue;
939
- }
940
- for (const key of keys) {
941
- keysToRemove.add(key);
942
- }
943
- }
944
- let removed = 0;
945
- for (const key of keysToRemove) {
946
- if (this.invalidate(key)) {
947
- removed += 1;
948
- }
949
- }
950
- for (const tag of tags) {
951
- this.tagIndex.delete(tag);
952
- }
953
- return removed;
954
- }
955
- invalidate(key) {
956
- const removed = this.cache.delete(key);
957
- if (removed) {
958
- this.detachKeyFromTags(key);
959
- }
960
- return removed;
961
- }
962
- invalidateByPrefix(prefix) {
963
- let removed = 0;
964
- for (const key of [...this.cache.keys()]) {
965
- if (key === prefix || key.startsWith(`${prefix}?`)) {
966
- if (this.invalidate(key)) {
967
- removed += 1;
968
- }
969
- }
970
- }
971
- return removed;
972
- }
973
- clear() {
974
- this.cache.clear();
975
- this.inflight.clear();
976
- this.tagIndex.clear();
977
- this.keyTags.clear();
978
- }
979
- size() {
980
- this.pruneExpired();
981
- return this.cache.size;
982
- }
983
- detachKeyFromTags(key) {
984
- const tags = this.keyTags.get(key);
985
- if (!tags) {
986
- return;
987
- }
988
- for (const tag of tags) {
989
- const keys = this.tagIndex.get(tag);
990
- if (!keys) {
991
- continue;
992
- }
993
- keys.delete(key);
994
- if (keys.size === 0) {
995
- this.tagIndex.delete(tag);
996
- }
997
- }
998
- this.keyTags.delete(key);
999
- }
1000
- getFreshEntry(key) {
1001
- const entry = this.cache.get(key);
1002
- if (!entry) {
1003
- return;
1004
- }
1005
- if (entry.expiresAt <= Date.now()) {
1006
- this.invalidate(key);
1007
- return;
1008
- }
1009
- entry.lastAccessedAt = Date.now();
1010
- return entry;
1011
- }
1012
- pruneExpired() {
1013
- const now = Date.now();
1014
- for (const [key, entry] of this.cache.entries()) {
1015
- if (entry.expiresAt <= now) {
1016
- this.invalidate(key);
1017
- }
1018
- }
1019
- }
1020
- evictOverflow() {
1021
- while (this.cache.size > this.maxEntries) {
1022
- let oldestKey;
1023
- let oldestAccessTime = Number.POSITIVE_INFINITY;
1024
- for (const [key, entry] of this.cache.entries()) {
1025
- if (entry.lastAccessedAt < oldestAccessTime) {
1026
- oldestAccessTime = entry.lastAccessedAt;
1027
- oldestKey = key;
1028
- }
1029
- }
1030
- if (!oldestKey) {
1031
- return;
1032
- }
1033
- this.invalidate(oldestKey);
1034
- }
1035
- }
1036
- }
1037
- var simpleCache_default = SimpleCache;
1038
-
1039
- // ../../src/core/cache/simpleCacheStore.ts
1040
- class SimpleCacheStore {
1041
- cache;
1042
- constructor(cache) {
1043
- this.cache = cache;
1044
- }
1045
- get(key) {
1046
- return Promise.resolve(this.cache.get(key));
1047
- }
1048
- set(key, value, ttlMs) {
1049
- this.cache.set(key, value, ttlMs);
1050
- return Promise.resolve();
1051
- }
1052
- getOrSet(key, loader, ttlMs) {
1053
- return this.cache.getOrSet(key, loader, ttlMs);
1054
- }
1055
- attachTags(key, tags) {
1056
- this.cache.attachTags(key, tags);
1057
- return Promise.resolve();
1058
- }
1059
- flushTags(tags) {
1060
- return Promise.resolve(this.cache.flushTags(tags));
1061
- }
1062
- invalidate(key) {
1063
- return Promise.resolve(this.cache.invalidate(key));
1064
- }
1065
- invalidateByPrefix(prefix) {
1066
- return Promise.resolve(this.cache.invalidateByPrefix(prefix));
1067
- }
1068
- clear() {
1069
- this.cache.clear();
1070
- return Promise.resolve();
1071
- }
1072
- size() {
1073
- return Promise.resolve(this.cache.size());
1074
- }
1075
- }
1076
- var simpleCacheStore_default = SimpleCacheStore;
1077
-
1078
- // ../../src/core/cache/createCacheStore.ts
1079
- function createCacheStore(options) {
1080
- if (options.driver === "redis") {
1081
- if (!options.redisUrl) {
1082
- throw new Error('CACHE_DRIVER="redis" requires REDIS_URL to be set.');
1083
- }
1084
- return new redisCacheStore_default(options.redisUrl, options.ttlMs, options.maxEntries);
1085
- }
1086
- return new simpleCacheStore_default(new simpleCache_default(options.ttlMs, options.maxEntries));
1087
- }
610
+ // ../../src/bootstrap/providers/cache.ts
611
+ import { createCacheStore } from "@getstrata/core/cache/createCacheStore";
1088
612
 
1089
613
  // ../../src/core/cache/taggedCache.ts
1090
614
  class TaggedCache {
@@ -1162,6 +686,9 @@ var cacheProvider = {
1162
686
  };
1163
687
  var cache_default = cacheProvider;
1164
688
 
689
+ // ../../src/bootstrap/providers/config.ts
690
+ import { validateEnv } from "@getstrata/core/config/envSchema";
691
+
1165
692
  // ../../src/config/app.ts
1166
693
  var appConfig = {
1167
694
  name: "WorkHub",
@@ -1178,34 +705,6 @@ var queueConfig = {
1178
705
  backoffMs: Number(process.env.QUEUE_BACKOFF_MS ?? "1000")
1179
706
  };
1180
707
 
1181
- // ../../src/core/config/envSchema.ts
1182
- function validateEnv(schema, env = process.env) {
1183
- const resolved = {};
1184
- for (const [name, rule] of Object.entries(schema)) {
1185
- const rawValue = env[name];
1186
- const value = rawValue === undefined || rawValue.trim() === "" ? rule.default : rawValue;
1187
- if (value === undefined || value.trim() === "") {
1188
- if (rule.required) {
1189
- throw new Error(`Missing required environment variable "${name}".`);
1190
- }
1191
- continue;
1192
- }
1193
- if (rule.integer) {
1194
- const parsed = Number.parseInt(value, 10);
1195
- const minimum = rule.minimum ?? Number.NEGATIVE_INFINITY;
1196
- if (!Number.isInteger(parsed) || parsed < minimum) {
1197
- const comparison = minimum === Number.NEGATIVE_INFINITY ? "an integer" : `an integer >= ${minimum}`;
1198
- throw new Error(`Environment variable "${name}" must be ${comparison}.`);
1199
- }
1200
- }
1201
- if (rule.pattern && !rule.pattern.test(value)) {
1202
- throw new Error(`Environment variable "${name}" has an invalid format.`);
1203
- }
1204
- resolved[name] = value;
1205
- }
1206
- return resolved;
1207
- }
1208
-
1209
708
  // ../../src/bootstrap/env.ts
1210
709
  import { defineEnvSchema } from "@getstrata/core/config/envSchema";
1211
710
  var appEnvSchema = defineEnvSchema({
@@ -1325,39 +824,8 @@ var configProvider = {
1325
824
  };
1326
825
  var config_default = configProvider;
1327
826
 
1328
- // ../../src/core/events/eventBus.ts
1329
- class EventBus {
1330
- constructor() {}
1331
- listeners = new Map;
1332
- listen(event, listener) {
1333
- const handlers = this.listeners.get(event) ?? new Set;
1334
- handlers.add(listener);
1335
- this.listeners.set(event, handlers);
1336
- return () => {
1337
- handlers.delete(listener);
1338
- if (handlers.size === 0) {
1339
- this.listeners.delete(event);
1340
- }
1341
- };
1342
- }
1343
- async dispatch(event, payload) {
1344
- const handlers = this.listeners.get(event);
1345
- if (!handlers || handlers.size === 0) {
1346
- return;
1347
- }
1348
- for (const handler of handlers) {
1349
- await handler(payload);
1350
- }
1351
- }
1352
- }
1353
- var eventBus = new EventBus;
1354
-
1355
- // ../../src/core/events/index.ts
1356
- function modelEventName(tableName, action) {
1357
- return `${tableName}.${action}`;
1358
- }
1359
-
1360
827
  // ../../src/bootstrap/providers/events.ts
828
+ import { eventBus } from "@getstrata/core/events";
1361
829
  var eventsProvider = {
1362
830
  name: "core.events",
1363
831
  register({ container }) {
@@ -1393,1971 +861,45 @@ function discoverListeners() {
1393
861
  return appListeners;
1394
862
  }
1395
863
 
1396
- // ../../src/core/queue/index.ts
1397
- class Job {
1398
- maxAttempts;
1399
- backoffMs;
1400
- priority;
1401
- }
864
+ // ../../src/bootstrap/listeners/invalidateCacheOnModelWrite.ts
865
+ import { eventBus as eventBus2, modelEventName } from "@getstrata/core/events";
866
+ import InvalidateCacheTagsJob from "@getstrata/core/jobs/invalidateCacheTagsJob";
867
+ import { createTrackedJob } from "@getstrata/core/queue/createAppQueue";
1402
868
 
1403
- // ../../src/core/jobs/invalidateCacheTagsJob.ts
1404
- class InvalidateCacheTagsJob extends Job {
1405
- cache;
1406
- constructor(cache) {
1407
- super();
1408
- this.cache = cache;
1409
- }
1410
- async handle(payload) {
1411
- await this.cache.tags(...payload.tags).flush();
1412
- }
869
+ // ../../src/bootstrap/cache/modelCacheTags.ts
870
+ function cacheTagsForModelWrite(tableName, action) {
871
+ const module = discoverModules().find((entry) => entry.tableName === tableName);
872
+ const baseTags = module?.cacheTags ?? [`${tableName}s`];
873
+ const isDelete = action === "deleted" || action === "force-deleted";
874
+ const extraTags = isDelete ? module?.cacheDeleteExtraTags ?? [] : [];
875
+ return [...new Set([...baseTags, ...extraTags])];
1413
876
  }
1414
- var invalidateCacheTagsJob_default = InvalidateCacheTagsJob;
1415
-
1416
- // ../../src/core/pagination/index.ts
1417
- function buildPaginationMeta(input) {
1418
- const lastPage = Math.max(1, Math.ceil(input.total / input.perPage));
1419
- return {
1420
- page: input.page,
1421
- per_page: input.perPage,
1422
- total: input.total,
1423
- last_page: lastPage
1424
- };
877
+ function discoverModelTableNames() {
878
+ return discoverModules().map((module) => module.tableName).filter((tableName) => tableName !== undefined);
1425
879
  }
1426
880
 
1427
- // ../../src/core/database/errors.ts
1428
- function isPostgresError(error) {
1429
- return typeof error === "object" && error !== null && (("errno" in error) || ("code" in error));
1430
- }
1431
- function getPostgresSqlState(error) {
1432
- if (typeof error.errno === "string" && /^\d{5}$/.test(error.errno)) {
1433
- return error.errno;
1434
- }
1435
- if (typeof error.errno === "number") {
1436
- return String(error.errno).padStart(5, "0");
1437
- }
1438
- if (typeof error.code === "string" && /^\d{5}$/.test(error.code)) {
1439
- return error.code;
1440
- }
1441
- return;
1442
- }
1443
- function mapDatabaseError(error) {
1444
- if (error instanceof HttpError) {
1445
- return error;
1446
- }
1447
- if (!isPostgresError(error)) {
1448
- const message = error instanceof Error ? error.message : "Database operation failed.";
1449
- return new BadRequestError(message);
1450
- }
1451
- const sqlState = getPostgresSqlState(error);
1452
- switch (sqlState) {
1453
- case "23505":
1454
- return new ConflictError(error.detail ?? "A record with these values already exists.", {
1455
- constraint: error.constraint
1456
- });
1457
- case "23503":
1458
- return new UnprocessableEntityError(error.detail ?? "Referenced record does not exist.", {
1459
- constraint: error.constraint
1460
- });
1461
- case "23502":
1462
- return new BadRequestError(error.detail ?? "Required field is missing.", {
1463
- constraint: error.constraint
1464
- });
1465
- case "23514":
1466
- return new BadRequestError(error.detail ?? "Value violates a database constraint.", {
1467
- constraint: error.constraint
1468
- });
1469
- default:
1470
- return new BadRequestError(error.message ?? "Database operation failed.", {
1471
- code: error.code,
1472
- sqlState
1473
- });
1474
- }
1475
- }
1476
- async function withDatabaseErrorHandling(operation) {
1477
- try {
1478
- return await operation();
1479
- } catch (error) {
1480
- throw mapDatabaseError(error);
1481
- }
1482
- }
1483
-
1484
- // ../../src/core/database/query.ts
1485
- function quoteIdentifier(identifier) {
1486
- if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(identifier)) {
1487
- throw new Error(`Invalid SQL identifier: ${identifier}`);
1488
- }
1489
- return `"${identifier}"`;
1490
- }
1491
- function qualifyColumn(tableName, column) {
1492
- return `${quoteIdentifier(tableName)}.${quoteIdentifier(column)}`;
1493
- }
1494
- function resolveQualifiedColumn(defaultTable, columnName) {
1495
- if (columnName.includes(".")) {
1496
- const [table, column] = columnName.split(".", 2);
1497
- if (!table || !column) {
1498
- throw new Error(`Invalid qualified column: ${columnName}`);
1499
- }
1500
- return qualifyColumn(table, column);
1501
- }
1502
- return qualifyColumn(defaultTable, columnName);
1503
- }
1504
- function parseQualifiedColumn(reference) {
1505
- const [table, column] = reference.split(".", 2);
1506
- if (!table || !column) {
1507
- throw new Error(`Join columns must be qualified as table.column: ${reference}`);
1508
- }
1509
- return { table, column };
1510
- }
1511
- function normalizeDirection(direction = "ASC") {
1512
- return direction.toUpperCase() === "DESC" ? "DESC" : "ASC";
1513
- }
1514
- function isQueryOperator(value) {
1515
- return value !== null && !Array.isArray(value) && !(value instanceof Date) && typeof value === "object";
1516
- }
1517
- function pushParam(values, value) {
1518
- values.push(value);
1519
- return `$${values.length}`;
1520
- }
1521
- function buildInClause(column, values, params) {
1522
- if (values.length === 0) {
1523
- return "1 = 0";
1524
- }
1525
- const placeholders = values.map((value) => pushParam(params, value)).join(", ");
1526
- return `${column} IN (${placeholders})`;
1527
- }
1528
- function buildOperatorClauses(column, operator, params) {
1529
- const clauses = [];
1530
- if (operator.isNull === true) {
1531
- clauses.push(`${column} IS NULL`);
1532
- }
1533
- if (operator.isNull === false) {
1534
- clauses.push(`${column} IS NOT NULL`);
1535
- }
1536
- if (operator.eq !== undefined) {
1537
- if (operator.eq === null) {
1538
- clauses.push(`${column} IS NULL`);
1539
- } else {
1540
- clauses.push(`${column} = ${pushParam(params, operator.eq)}`);
1541
- }
1542
- }
1543
- if (operator.in !== undefined) {
1544
- clauses.push(buildInClause(column, operator.in, params));
1545
- }
1546
- if (operator.gt !== undefined) {
1547
- clauses.push(`${column} > ${pushParam(params, operator.gt)}`);
1548
- }
1549
- if (operator.gte !== undefined) {
1550
- clauses.push(`${column} >= ${pushParam(params, operator.gte)}`);
1551
- }
1552
- if (operator.lt !== undefined) {
1553
- clauses.push(`${column} < ${pushParam(params, operator.lt)}`);
1554
- }
1555
- if (operator.lte !== undefined) {
1556
- clauses.push(`${column} <= ${pushParam(params, operator.lte)}`);
1557
- }
1558
- if (operator.ilike !== undefined) {
1559
- clauses.push(`${column} ILIKE ${pushParam(params, `%${operator.ilike}%`)}`);
1560
- }
1561
- if (operator.tsMatch !== undefined) {
1562
- clauses.push(`${column} @@ plainto_tsquery('english', ${pushParam(params, operator.tsMatch)})`);
1563
- }
1564
- return clauses;
1565
- }
1566
- function appendWhereParts(tableName, where, params) {
1567
- const clauses = [];
1568
- for (const [columnName, filterValue] of Object.entries(where)) {
1569
- if (filterValue === undefined) {
1570
- continue;
1571
- }
1572
- const column = resolveQualifiedColumn(tableName, columnName);
1573
- if (Array.isArray(filterValue)) {
1574
- clauses.push(buildInClause(column, filterValue, params));
1575
- continue;
1576
- }
1577
- if (isQueryOperator(filterValue)) {
1578
- clauses.push(...buildOperatorClauses(column, filterValue, params));
1579
- continue;
1580
- }
1581
- if (filterValue === null) {
1582
- clauses.push(`${column} IS NULL`);
1583
- continue;
1584
- }
1585
- clauses.push(`${column} = ${pushParam(params, filterValue)}`);
1586
- }
1587
- return clauses.join(" AND ");
1588
- }
1589
- function buildWhereNodeClause(tableName, node, params) {
1590
- if ("where" in node) {
1591
- return appendWhereParts(tableName, node.where, params);
1592
- }
1593
- const grouped = buildWhereGroupClause(tableName, node.group, params);
1594
- if (!grouped) {
1595
- return "";
1596
- }
1597
- return grouped.includes(" OR ") ? `(${grouped})` : grouped;
1598
- }
1599
- function buildWhereGroupClause(tableName, nodes, params) {
1600
- let result = "";
1601
- for (const node of nodes) {
1602
- const part = buildWhereNodeClause(tableName, node, params);
1603
- if (!part) {
1604
- continue;
1605
- }
1606
- if (!result) {
1607
- result = part;
1608
- continue;
1609
- }
1610
- result = node.kind === "or" ? `${result} OR ${part}` : `${result} AND ${part}`;
1611
- }
1612
- if (!result) {
1613
- return "";
1614
- }
1615
- return result;
1616
- }
1617
- function buildAdvancedWhereClause(tableName, where = {}, whereNodes = [], params = []) {
1618
- const nodes = [];
1619
- if (Object.keys(where).length > 0) {
1620
- nodes.push({ kind: "and", where });
1621
- }
1622
- nodes.push(...whereNodes);
1623
- const combined = buildWhereGroupClause(tableName, nodes, params);
1624
- return {
1625
- clause: combined ? ` WHERE ${combined}` : "",
1626
- params
1627
- };
1628
- }
1629
- function resolveSoftDeleteColumn(table) {
1630
- if (!table.softDeletes) {
1631
- return null;
1632
- }
1633
- if (table.softDeletes === true) {
1634
- return "deleted_at";
1635
- }
1636
- return table.softDeletes.column ?? "deleted_at";
1637
- }
1638
- function appendSoftDeleteScope(table, options, clauses) {
1639
- const column = resolveSoftDeleteColumn(table);
1640
- if (!column) {
1641
- return;
1642
- }
1643
- const qualifiedColumn = qualifyColumn(table.name, column);
1644
- if (options.onlyTrashed) {
1645
- clauses.push(`${qualifiedColumn} IS NOT NULL`);
1646
- return;
1647
- }
1648
- if (!options.withTrashed) {
1649
- clauses.push(`${qualifiedColumn} IS NULL`);
1650
- }
1651
- }
1652
- function buildQueryWhereClause(table, options = {}, whereNodes = [], params = []) {
1653
- const { clause, params: whereParams } = buildAdvancedWhereClause(table.name, options.where ?? {}, whereNodes, params);
1654
- const softDeleteClauses = [];
1655
- appendSoftDeleteScope(table, options, softDeleteClauses);
1656
- if (softDeleteClauses.length === 0) {
1657
- return { clause, params: whereParams };
1658
- }
1659
- const base = clause.replace(/^ WHERE /, "");
1660
- const scope = softDeleteClauses.join(" AND ");
1661
- return {
1662
- clause: base ? ` WHERE (${base}) AND ${scope}` : ` WHERE ${scope}`,
1663
- params: whereParams
1664
- };
1665
- }
1666
- function isQueryOrder(value) {
1667
- return "column" in value;
1668
- }
1669
- function normalizeOrderBy(orderBy) {
1670
- if (!orderBy) {
1671
- return [];
1672
- }
1673
- if (Array.isArray(orderBy)) {
1674
- return orderBy;
1675
- }
1676
- if (isQueryOrder(orderBy)) {
1677
- return [orderBy];
1678
- }
1679
- return Object.entries(orderBy).map(([column, direction]) => ({
1680
- column,
1681
- direction
1682
- }));
1683
- }
1684
- function buildOrderByClause(tableName, orderBy) {
1685
- const parts = normalizeOrderBy(orderBy).map(({ column, direction }) => {
1686
- return `${resolveQualifiedColumn(tableName, column)} ${normalizeDirection(direction)}`;
1687
- });
1688
- return parts.length > 0 ? ` ORDER BY ${parts.join(", ")}` : "";
1689
- }
1690
- function buildGroupByClause(tableName, groupBy) {
1691
- if (!groupBy) {
1692
- return "";
1693
- }
1694
- const columns = (Array.isArray(groupBy) ? groupBy : [groupBy]).map((column) => String(column));
1695
- const parts = columns.map((column) => resolveQualifiedColumn(tableName, column));
1696
- return parts.length > 0 ? ` GROUP BY ${parts.join(", ")}` : "";
1697
- }
1698
- function buildHavingClause(tableName, having, params) {
1699
- if (!having) {
1700
- return "";
1701
- }
1702
- const body = appendWhereParts(tableName, having, params);
1703
- return body.length > 0 ? ` HAVING ${body}` : "";
1704
- }
1705
- function buildJoinClause(joins = []) {
1706
- return joins.map((join3) => {
1707
- const joinType = join3.type === "left" ? "LEFT JOIN" : "INNER JOIN";
1708
- const onClause = join3.on.map(({ left, right }) => `${qualifyColumn(left.table, left.column)} = ${qualifyColumn(right.table, right.column)}`).join(" AND ");
1709
- return ` ${joinType} ${quoteIdentifier(join3.table)} ON ${onClause}`;
1710
- }).join("");
1711
- }
1712
- function buildLimitClause(limit) {
1713
- if (limit === undefined) {
1714
- return "";
1715
- }
1716
- if (!Number.isInteger(limit) || limit <= 0) {
1717
- throw new Error("Query limit must be a positive integer.");
1718
- }
1719
- return ` LIMIT ${limit}`;
1720
- }
1721
- function buildOffsetClause(offset) {
1722
- if (offset === undefined) {
1723
- return "";
1724
- }
1725
- if (!Number.isInteger(offset) || offset < 0) {
1726
- throw new Error("Query offset must be a non-negative integer.");
1727
- }
1728
- return ` OFFSET ${offset}`;
1729
- }
1730
- function buildReturningColumns(table) {
1731
- return table.columns.map((column) => qualifyColumn(table.name, column)).join(", ");
1732
- }
1733
- function buildSelectList(table, select, params = []) {
1734
- if (!select || select.length === 0) {
1735
- return buildReturningColumns(table);
1736
- }
1737
- return select.map((item) => {
1738
- if (item.kind === "column") {
1739
- const column2 = qualifyColumn(item.table, item.column);
1740
- return item.as ? `${column2} AS ${quoteIdentifier(item.as)}` : column2;
1741
- }
1742
- if (item.kind === "literalText") {
1743
- return `${pushParam(params, item.value)}::text AS ${quoteIdentifier(item.as)}`;
1744
- }
1745
- const column = qualifyColumn(item.table, item.column);
1746
- const placeholder = pushParam(params, item.query);
1747
- return `ts_rank(${column}, plainto_tsquery('english', ${placeholder})) AS ${quoteIdentifier(item.as)}`;
1748
- }).join(", ");
1749
- }
1750
- function getDefinedColumnEntries(table, values, options = {}) {
1751
- const record = values;
1752
- const excluded = new Set(options.exclude ?? []);
1753
- return table.columns.flatMap((column) => {
1754
- if (excluded.has(column) || !Object.hasOwn(record, column)) {
1755
- return [];
1756
- }
1757
- const value = record[column];
1758
- if (value === undefined) {
1759
- return [];
1760
- }
1761
- return [[column, value]];
1762
- });
1763
- }
1764
- function buildSelectQuery(table, options = {}, whereNodes = []) {
1765
- const params = [];
1766
- const columns = buildSelectList(table, options.select, params);
1767
- const { clause } = buildQueryWhereClause(table, options, whereNodes, params);
1768
- const joins = buildJoinClause(options.joins);
1769
- const groupBy = buildGroupByClause(table.name, options.groupBy);
1770
- const havingClause = buildHavingClause(table.name, options.having, params);
1771
- const orderBy = buildOrderByClause(table.name, options.orderBy ?? table.defaultOrderBy);
1772
- const limit = buildLimitClause(options.limit);
1773
- const offset = buildOffsetClause(options.offset);
1774
- return {
1775
- text: `SELECT ${columns} FROM ${quoteIdentifier(table.name)}${joins}${clause}${groupBy}${havingClause}${orderBy}${limit}${offset}`,
1776
- params
1777
- };
1778
- }
1779
- function buildCountQuery(table, where = {}, options = {}, whereNodes = []) {
1780
- const params = [];
1781
- const { clause, params: whereParams } = buildQueryWhereClause(table, {
1782
- where,
1783
- withTrashed: options.withTrashed,
1784
- onlyTrashed: options.onlyTrashed
1785
- }, whereNodes);
1786
- params.push(...whereParams);
1787
- const joins = buildJoinClause(options.joins);
1788
- const groupBy = buildGroupByClause(table.name, options.groupBy);
1789
- return {
1790
- text: `SELECT COUNT(*) AS count FROM ${quoteIdentifier(table.name)}${joins}${clause}${groupBy}`,
1791
- params
1792
- };
1793
- }
1794
- function buildProjectionQuery(table, expression, alias, options = {}, whereNodes = []) {
1795
- assertSafeProjectionExpression(expression);
1796
- const params = [];
1797
- const { clause, params: whereParams } = buildQueryWhereClause(table, options, whereNodes);
1798
- params.push(...whereParams);
1799
- const joins = buildJoinClause(options.joins);
1800
- const groupBy = buildGroupByClause(table.name, options.groupBy);
1801
- const orderBy = buildOrderByClause(table.name, options.orderBy);
1802
- const limit = buildLimitClause(options.limit);
1803
- return {
1804
- text: `SELECT ${expression} AS ${quoteIdentifier(alias)} FROM ${quoteIdentifier(table.name)}${joins}${clause}${groupBy}${orderBy}${limit}`,
1805
- params
1806
- };
1807
- }
1808
- var SAFE_PROJECTION_EXPRESSION = /^(COUNT\(\*\)|(?:"[\w_]+"(?:\."[\w_]+")?)|(?:AVG|SUM|MIN|MAX)\((?:"[\w_]+"(?:\."[\w_]+")?)\))$/;
1809
- function assertSafeProjectionExpression(expression) {
1810
- if (!SAFE_PROJECTION_EXPRESSION.test(expression.trim())) {
1811
- throw new Error(`Unsafe projection expression: ${expression}`);
1812
- }
1813
- }
1814
- function buildGroupedCountQuery(table, column, where = {}, options = {}) {
1815
- const qualifiedColumn = qualifyColumn(table.name, column);
1816
- const { clause, params } = buildQueryWhereClause(table, {
1817
- where,
1818
- ...options
1819
- });
1820
- return {
1821
- text: `SELECT ${qualifiedColumn} AS ${quoteIdentifier("value")}, COUNT(*) AS ${quoteIdentifier("count")} FROM ${quoteIdentifier(table.name)}${clause} GROUP BY ${qualifiedColumn} ORDER BY ${qualifiedColumn} ASC`,
1822
- params
1823
- };
1824
- }
1825
- function buildInsertQuery(table, values) {
1826
- const entries = getDefinedColumnEntries(table, values);
1827
- if (entries.length === 0) {
1828
- throw new Error(`Cannot insert into ${table.name} without any column values.`);
1829
- }
1830
- const params = [];
1831
- const columns = entries.map(([column]) => quoteIdentifier(column)).join(", ");
1832
- const placeholders = entries.map(([, value]) => pushParam(params, value)).join(", ");
1833
- const returningColumns = buildReturningColumns(table);
1834
- return {
1835
- text: `INSERT INTO ${quoteIdentifier(table.name)} (${columns}) VALUES (${placeholders}) RETURNING ${returningColumns}`,
1836
- params
1837
- };
1838
- }
1839
- function buildUpdateQuery(table, id, changes) {
1840
- const entries = getDefinedColumnEntries(table, changes, {
1841
- exclude: [table.primaryKey]
1842
- });
1843
- if (entries.length === 0) {
1844
- throw new Error(`Cannot update ${table.name} without any changed column values.`);
1845
- }
1846
- const params = [];
1847
- const setClause = entries.map(([column, value]) => `${quoteIdentifier(column)} = ${pushParam(params, value)}`).join(", ");
1848
- const primaryKeyPlaceholder = pushParam(params, id);
1849
- const returningColumns = buildReturningColumns(table);
1850
- const scopeClauses = [];
1851
- appendSoftDeleteScope(table, {}, scopeClauses);
1852
- const scopeSuffix = scopeClauses.length > 0 ? ` AND ${scopeClauses.join(" AND ")}` : "";
1853
- return {
1854
- text: `UPDATE ${quoteIdentifier(table.name)} SET ${setClause} WHERE ${quoteIdentifier(table.primaryKey)} = ${primaryKeyPlaceholder}${scopeSuffix} RETURNING ${returningColumns}`,
1855
- params
1856
- };
1857
- }
1858
- function buildSoftDeleteByIdQuery(table, id, deletedAt) {
1859
- const deletedAtColumn = resolveSoftDeleteColumn(table);
1860
- if (!deletedAtColumn) {
1861
- throw new Error(`Table ${table.name} does not support soft deletes.`);
1862
- }
1863
- const returningColumns = buildReturningColumns(table);
1864
- const scopeClauses = [];
1865
- appendSoftDeleteScope(table, {}, scopeClauses);
1866
- const scopeSuffix = scopeClauses.length > 0 ? ` AND ${scopeClauses.join(" AND ")}` : "";
1867
- return {
1868
- text: `UPDATE ${quoteIdentifier(table.name)} SET ${quoteIdentifier(deletedAtColumn)} = $1 WHERE ${quoteIdentifier(table.primaryKey)} = $2${scopeSuffix} RETURNING ${returningColumns}`,
1869
- params: [deletedAt, id]
1870
- };
1871
- }
1872
- function buildRestoreByIdQuery(table, id) {
1873
- const deletedAtColumn = resolveSoftDeleteColumn(table);
1874
- if (!deletedAtColumn) {
1875
- throw new Error(`Table ${table.name} does not support soft deletes.`);
1876
- }
1877
- const returningColumns = buildReturningColumns(table);
1878
- return {
1879
- text: `UPDATE ${quoteIdentifier(table.name)} SET ${quoteIdentifier(deletedAtColumn)} = $1 WHERE ${quoteIdentifier(table.primaryKey)} = $2 AND ${qualifyColumn(table.name, deletedAtColumn)} IS NOT NULL RETURNING ${returningColumns}`,
1880
- params: [null, id]
1881
- };
1882
- }
1883
- function buildDeleteByIdQuery(table, id) {
1884
- return {
1885
- text: `DELETE FROM ${quoteIdentifier(table.name)} WHERE ${quoteIdentifier(table.primaryKey)} = $1 RETURNING ${quoteIdentifier(table.primaryKey)} AS ${quoteIdentifier("deleted_id")}`,
1886
- params: [id]
1887
- };
1888
- }
1889
-
1890
- // ../../src/core/database/relationships.ts
1891
- function indexHasManyRelation(parents, children, relation) {
1892
- const groups = new Map;
1893
- for (const parent of parents) {
1894
- groups.set(parent[relation.localKey], []);
1895
- }
1896
- for (const child of children) {
1897
- const key = child[relation.foreignKey];
1898
- const group = groups.get(key);
1899
- if (!group) {
1900
- continue;
1901
- }
1902
- group.push(child);
1903
- }
1904
- return groups;
1905
- }
1906
- function indexBelongsToRelation(children, parents, relation) {
1907
- const parentsById = new Map;
1908
- for (const parent of parents) {
1909
- parentsById.set(parent[relation.ownerKey], parent);
1910
- }
1911
- const result = new Map;
1912
- for (const child of children) {
1913
- const foreignKey = child[relation.foreignKey];
1914
- const parent = parentsById.get(foreignKey);
1915
- if (parent) {
1916
- result.set(foreignKey, parent);
1917
- }
1918
- }
1919
- return result;
1920
- }
1921
- function indexMorphManyRelation(parents, children, relation) {
1922
- const groups = new Map;
1923
- for (const parent of parents) {
1924
- groups.set(parent[relation.localKey], []);
1925
- }
1926
- for (const child of children) {
1927
- if (child[relation.morphTypeKey] !== relation.morphType) {
1928
- continue;
1929
- }
1930
- const key = child[relation.morphIdKey];
1931
- const group = groups.get(key);
1932
- if (!group) {
1933
- continue;
1934
- }
1935
- group.push(child);
1936
- }
1937
- return groups;
1938
- }
1939
- function indexMorphToRelation(children, parentsByType, relation) {
1940
- const result = new Map;
1941
- for (const child of children) {
1942
- const morphType = String(child[relation.morphTypeKey]);
1943
- const parents = parentsByType.get(morphType);
1944
- if (!parents) {
1945
- continue;
1946
- }
1947
- const parent = parents.get(child[relation.morphIdKey]);
1948
- if (parent) {
1949
- result.set(child[relation.morphIdKey], parent);
1950
- }
1951
- }
1952
- return result;
1953
- }
1954
-
1955
- // ../../src/core/database/boundConnection.ts
1956
- var boundConnectionHolder = {
1957
- connection: null
1958
- };
1959
- function getBoundDatabaseConnection() {
1960
- return boundConnectionHolder.connection;
1961
- }
1962
-
1963
- // ../../src/core/database/repositoryConnection.ts
1964
- function resolveRepositoryConnection() {
1965
- return getBoundDatabaseConnection() ?? getDefaultDatabaseQuery();
1966
- }
1967
- var repositoryConnection = new Proxy(function repositoryConnection2() {}, {
1968
- apply(_target, _thisArg, args) {
1969
- return resolveRepositoryConnection()(...args);
1970
- },
1971
- get(_target, property) {
1972
- const connection = resolveRepositoryConnection();
1973
- const value = connection[property];
1974
- return typeof value === "function" ? value.bind(connection) : value;
1975
- }
1976
- });
1977
-
1978
- // ../../src/core/database/whereBuilder.ts
1979
- class WhereBuilder {
1980
- nodes = [];
1981
- where(where) {
1982
- this.nodes.push({ kind: "and", where });
1983
- return this;
1984
- }
1985
- orWhere(where) {
1986
- this.nodes.push({ kind: "or", where });
1987
- return this;
1988
- }
1989
- whereGroup(fn) {
1990
- const nested = new WhereBuilder;
1991
- fn(nested);
1992
- if (nested.nodes.length > 0) {
1993
- this.nodes.push({ kind: "and", group: nested.nodes });
1994
- }
1995
- return this;
1996
- }
1997
- orWhereGroup(fn) {
1998
- const nested = new WhereBuilder;
1999
- fn(nested);
2000
- if (nested.nodes.length > 0) {
2001
- this.nodes.push({ kind: "or", group: nested.nodes });
2002
- }
2003
- return this;
2004
- }
2005
- }
2006
-
2007
- // ../../src/core/database/repositoryQuery.ts
2008
- class RepositoryQuery {
2009
- repository;
2010
- whereClause;
2011
- queryOptions;
2012
- eagerLoads = [];
2013
- whereNodes = [];
2014
- constructor(repository, whereClause = {}, queryOptions = {}) {
2015
- this.repository = repository;
2016
- this.whereClause = whereClause;
2017
- this.queryOptions = queryOptions;
2018
- }
2019
- where(input) {
2020
- if (typeof input === "function") {
2021
- const builder = new WhereBuilder;
2022
- input(builder);
2023
- this.whereNodes.push(...builder.nodes);
2024
- return this;
2025
- }
2026
- this.whereClause = { ...this.whereClause, ...input };
2027
- return this;
2028
- }
2029
- orWhere(input) {
2030
- if (typeof input === "function") {
2031
- const builder = new WhereBuilder;
2032
- input(builder);
2033
- if (builder.nodes.length > 0) {
2034
- this.whereNodes.push({ kind: "or", group: builder.nodes });
2035
- }
2036
- return this;
2037
- }
2038
- this.whereNodes.push({ kind: "or", where: input });
2039
- return this;
2040
- }
2041
- orderBy(orderBy) {
2042
- this.queryOptions = { ...this.queryOptions, orderBy };
2043
- return this;
2044
- }
2045
- limit(limit) {
2046
- this.queryOptions = { ...this.queryOptions, limit };
2047
- return this;
2048
- }
2049
- offset(offset) {
2050
- this.queryOptions = { ...this.queryOptions, offset };
2051
- return this;
2052
- }
2053
- join(left, right) {
2054
- return this.addJoin("inner", left, right);
2055
- }
2056
- leftJoin(left, right) {
2057
- return this.addJoin("left", left, right);
2058
- }
2059
- groupBy(groupBy) {
2060
- this.queryOptions = { ...this.queryOptions, groupBy };
2061
- return this;
2062
- }
2063
- having(having) {
2064
- this.queryOptions = { ...this.queryOptions, having };
2065
- return this;
2066
- }
2067
- withHasMany(as, relation, childRepository, options = {}) {
2068
- this.eagerLoads.push({
2069
- kind: "hasMany",
2070
- as,
2071
- relation,
2072
- repository: childRepository,
2073
- options
2074
- });
2075
- return this;
2076
- }
2077
- withBelongsTo(as, relation, parentRepository, options = {}) {
2078
- this.eagerLoads.push({
2079
- kind: "belongsTo",
2080
- as,
2081
- relation,
2082
- repository: parentRepository,
2083
- options
2084
- });
2085
- return this;
2086
- }
2087
- withMorphMany(as, relation, childRepository, options = {}) {
2088
- this.eagerLoads.push({
2089
- kind: "morphMany",
2090
- as,
2091
- relation,
2092
- repository: childRepository,
2093
- options
2094
- });
2095
- return this;
2096
- }
2097
- withMorphOne(as, relation, childRepository, options = {}) {
2098
- this.eagerLoads.push({
2099
- kind: "morphOne",
2100
- as,
2101
- relation,
2102
- repository: childRepository,
2103
- options
2104
- });
2105
- return this;
2106
- }
2107
- withMorphTo(as, relation, repositoriesByType, options = {}) {
2108
- this.eagerLoads.push({
2109
- kind: "morphTo",
2110
- as,
2111
- relation,
2112
- repository: this.repository,
2113
- morphRepositories: repositoriesByType,
2114
- options
2115
- });
2116
- return this;
2117
- }
2118
- async get() {
2119
- const rows = await this.repository.findAll(this.buildOptions());
2120
- return await this.attach(rows);
2121
- }
2122
- async first() {
2123
- const rows = await this.get();
2124
- return rows[0] ?? null;
2125
- }
2126
- async paginate(options) {
2127
- return await this.repository.paginate({
2128
- ...this.buildOptions(),
2129
- page: options.page,
2130
- perPage: options.perPage
2131
- });
2132
- }
2133
- buildOptions() {
2134
- return {
2135
- ...this.queryOptions,
2136
- where: this.whereClause,
2137
- whereNodes: this.whereNodes
2138
- };
2139
- }
2140
- addJoin(type, left, right) {
2141
- const leftRef = parseQualifiedColumn(left);
2142
- const rightRef = parseQualifiedColumn(right);
2143
- const table = type === "inner" ? rightRef.table : rightRef.table;
2144
- const joins = this.queryOptions.joins ?? [];
2145
- const existing = joins.find((join3) => join3.table === table && join3.type === type);
2146
- if (existing) {
2147
- existing.on.push({ left: leftRef, right: rightRef });
2148
- return this;
2149
- }
2150
- this.queryOptions = {
2151
- ...this.queryOptions,
2152
- joins: [
2153
- ...joins,
2154
- {
2155
- type,
2156
- table,
2157
- on: [{ left: leftRef, right: rightRef }]
2158
- }
2159
- ]
2160
- };
2161
- return this;
2162
- }
2163
- async attach(rows) {
2164
- if (rows.length === 0 || this.eagerLoads.length === 0) {
2165
- return rows.map((row) => ({ ...row }));
2166
- }
2167
- let result = rows.map((row) => ({ ...row }));
2168
- for (const load of this.eagerLoads) {
2169
- if (load.kind === "hasMany") {
2170
- const relation2 = load.relation;
2171
- const grouped2 = await load.repository.withConnection(this.repository.getConnection()).loadHasManyForParents(rows, relation2, load.options);
2172
- result = result.map((row) => ({
2173
- ...row,
2174
- [load.as]: grouped2.get(row[relation2.localKey]) ?? []
2175
- }));
2176
- continue;
2177
- }
2178
- if (load.kind === "morphMany") {
2179
- const relation2 = load.relation;
2180
- const grouped2 = await load.repository.withConnection(this.repository.getConnection()).loadMorphManyForParents(rows, relation2, load.options);
2181
- result = result.map((row) => ({
2182
- ...row,
2183
- [load.as]: grouped2.get(row[relation2.localKey]) ?? []
2184
- }));
2185
- continue;
2186
- }
2187
- if (load.kind === "morphOne") {
2188
- const relation2 = load.relation;
2189
- const grouped2 = await load.repository.withConnection(this.repository.getConnection()).loadMorphOneForParents(rows, relation2, load.options);
2190
- result = result.map((row) => ({
2191
- ...row,
2192
- [load.as]: grouped2.get(row[relation2.localKey])
2193
- }));
2194
- continue;
2195
- }
2196
- if (load.kind === "morphTo") {
2197
- const relation2 = load.relation;
2198
- const grouped2 = await this.repository.loadMorphToForChildren(rows, relation2, load.morphRepositories ?? new Map, load.options);
2199
- result = result.map((row) => ({
2200
- ...row,
2201
- [load.as]: grouped2.get(row[relation2.morphIdKey])
2202
- }));
2203
- continue;
2204
- }
2205
- const relation = load.relation;
2206
- const grouped = await this.repository.loadBelongsToForParents(rows, relation, load.repository, load.options);
2207
- result = result.map((row) => ({
2208
- ...row,
2209
- [load.as]: grouped.get(row[relation.foreignKey])
2210
- }));
2211
- }
2212
- return result;
2213
- }
2214
- }
2215
-
2216
- // ../../src/core/database/baseRepository.ts
2217
- class BaseRepository5 {
2218
- table;
2219
- connection;
2220
- constructor(table, connection = repositoryConnection) {
2221
- this.table = table;
2222
- this.connection = connection;
2223
- }
2224
- async findAll(options = {}) {
2225
- return await withDatabaseErrorHandling(async () => {
2226
- const { whereNodes, ...queryOptions } = options;
2227
- const { text, params } = buildSelectQuery(this.table, queryOptions, whereNodes ?? []);
2228
- return await this.connection.unsafe(text, params);
2229
- });
2230
- }
2231
- async paginate(options) {
2232
- const { whereNodes, where = {}, page, perPage, ...queryOptions } = options;
2233
- const total = await this.countWhere(where, {
2234
- withTrashed: options.withTrashed,
2235
- onlyTrashed: options.onlyTrashed,
2236
- joins: options.joins,
2237
- groupBy: options.groupBy
2238
- }, whereNodes);
2239
- const offset = (page - 1) * perPage;
2240
- const data = await this.findAll({
2241
- ...queryOptions,
2242
- where,
2243
- whereNodes,
2244
- limit: perPage,
2245
- offset
2246
- });
2247
- return {
2248
- data,
2249
- meta: buildPaginationMeta({ page, perPage, total })
2250
- };
2251
- }
2252
- async chunk(count, callback, options = {}) {
2253
- if (!Number.isInteger(count) || count <= 0) {
2254
- throw new Error("Chunk size must be a positive integer.");
2255
- }
2256
- let offset = 0;
2257
- while (true) {
2258
- const rows = await this.findAll({
2259
- ...options,
2260
- limit: count,
2261
- offset
2262
- });
2263
- if (rows.length === 0) {
2264
- return;
2265
- }
2266
- const shouldContinue = await callback(rows);
2267
- if (shouldContinue === false || rows.length < count) {
2268
- return;
2269
- }
2270
- offset += count;
2271
- }
2272
- }
2273
- async cursorPaginate(options) {
2274
- const {
2275
- perPage,
2276
- cursor,
2277
- cursorColumn = this.table.primaryKey,
2278
- direction = "asc",
2279
- where = {},
2280
- whereNodes,
2281
- ...queryOptions
2282
- } = options;
2283
- if (!Number.isInteger(perPage) || perPage <= 0) {
2284
- throw new Error("Cursor page size must be a positive integer.");
2285
- }
2286
- const cursorWhere = { ...where };
2287
- if (cursor !== undefined) {
2288
- cursorWhere[cursorColumn] = direction === "asc" ? { gt: cursor } : { lt: cursor };
2289
- }
2290
- const rows = await this.findAll({
2291
- ...queryOptions,
2292
- where: cursorWhere,
2293
- whereNodes,
2294
- orderBy: { [cursorColumn]: direction },
2295
- limit: perPage + 1
2296
- });
2297
- const hasMore = rows.length > perPage;
2298
- const data = hasMore ? rows.slice(0, perPage) : rows;
2299
- const nextCursor = hasMore ? data[data.length - 1]?.[cursorColumn] ?? null : null;
2300
- const prevCursor = cursor ?? null;
2301
- return {
2302
- data,
2303
- meta: {
2304
- per_page: perPage,
2305
- next_cursor: nextCursor,
2306
- prev_cursor: prevCursor,
2307
- has_more: hasMore
2308
- }
2309
- };
2310
- }
2311
- async findById(id) {
2312
- return await this.firstOrNull({
2313
- [this.table.primaryKey]: id
2314
- });
2315
- }
2316
- async findByIdOrThrow(id, errorFactory) {
2317
- const record = await this.findById(id);
2318
- if (record) {
2319
- return record;
2320
- }
2321
- throw errorFactory?.(id) ?? new Error(`${this.table.name} ${String(id)} was not found.`);
2322
- }
2323
- async findByIds(ids) {
2324
- const uniqueIds = [...new Set(ids)];
2325
- if (uniqueIds.length === 0) {
2326
- return [];
2327
- }
2328
- return await this.findWhere({
2329
- [this.table.primaryKey]: uniqueIds
2330
- });
2331
- }
2332
- async firstOrNull(where, options = {}) {
2333
- const [record] = await this.findAll({ ...options, where, limit: 1 });
2334
- return record ?? null;
2335
- }
2336
- async create(values) {
2337
- return await withDatabaseErrorHandling(async () => {
2338
- const { text, params } = buildInsertQuery(this.table, values);
2339
- const [record] = await this.connection.unsafe(text, params);
2340
- if (!record) {
2341
- throw new Error(`Insert into ${this.table.name} did not return a record.`);
2342
- }
2343
- const entity = record;
2344
- await eventBus.dispatch(modelEventName(this.table.name, "created"), entity);
2345
- return entity;
2346
- });
2347
- }
2348
- async updateById(id, changes) {
2349
- return await withDatabaseErrorHandling(async () => {
2350
- const { text, params } = buildUpdateQuery(this.table, id, changes);
2351
- const [record] = await this.connection.unsafe(text, params);
2352
- const entity = record ?? null;
2353
- if (entity) {
2354
- await eventBus.dispatch(modelEventName(this.table.name, "updated"), entity);
2355
- }
2356
- return entity;
2357
- });
2358
- }
2359
- async updateByIdOrThrow(id, changes, errorFactory) {
2360
- const record = await this.updateById(id, changes);
2361
- if (record) {
2362
- return record;
2363
- }
2364
- throw errorFactory?.(id) ?? new Error(`${this.table.name} ${String(id)} was not found.`);
2365
- }
2366
- async deleteById(id) {
2367
- if (resolveSoftDeleteColumn(this.table)) {
2368
- return await this.softDeleteById(id);
2369
- }
2370
- return await this.forceDeleteById(id);
2371
- }
2372
- async softDeleteById(id) {
2373
- return await withDatabaseErrorHandling(async () => {
2374
- const { text, params } = buildSoftDeleteByIdQuery(this.table, id, new Date);
2375
- const [record] = await this.connection.unsafe(text, params);
2376
- if (!record) {
2377
- return false;
2378
- }
2379
- await eventBus.dispatch(modelEventName(this.table.name, "deleted"), record);
2380
- return true;
2381
- });
2382
- }
2383
- async forceDeleteById(id) {
2384
- return await withDatabaseErrorHandling(async () => {
2385
- const { text, params } = buildDeleteByIdQuery(this.table, id);
2386
- const [row] = await this.connection.unsafe(text, params);
2387
- if (!row) {
2388
- return false;
2389
- }
2390
- await eventBus.dispatch(modelEventName(this.table.name, "force-deleted"), {
2391
- id
2392
- });
2393
- return true;
2394
- });
2395
- }
2396
- async restoreById(id) {
2397
- return await withDatabaseErrorHandling(async () => {
2398
- const { text, params } = buildRestoreByIdQuery(this.table, id);
2399
- const [record] = await this.connection.unsafe(text, params);
2400
- if (!record) {
2401
- return null;
2402
- }
2403
- const entity = record;
2404
- await eventBus.dispatch(modelEventName(this.table.name, "restored"), entity);
2405
- return entity;
2406
- });
2407
- }
2408
- withConnection(connection) {
2409
- const clone = Object.create(Object.getPrototypeOf(this));
2410
- Object.assign(clone, this);
2411
- clone.connection = connection;
2412
- return clone;
2413
- }
2414
- getConnection() {
2415
- return this.connection;
2416
- }
2417
- getTable() {
2418
- return this.table;
2419
- }
2420
- query(where = {}) {
2421
- return new RepositoryQuery(this, where);
2422
- }
2423
- async findWhere(where, options = {}) {
2424
- return await this.findAll({ ...options, where });
2425
- }
2426
- async countWhere(where = {}, options = {}, whereNodes = []) {
2427
- const { text, params } = buildCountQuery(this.table, where, options, whereNodes);
2428
- const [row] = await this.connection.unsafe(text, params);
2429
- return Number(row?.count ?? 0);
2430
- }
2431
- async averageColumn(column, where = {}) {
2432
- const qualifiedColumn = qualifyColumn(this.table.name, column);
2433
- return await this.averageExpression(`AVG(${qualifiedColumn})`, "value", where);
2434
- }
2435
- async averageExpression(expression, alias, where = {}) {
2436
- const { text, params } = buildProjectionQuery(this.table, expression, alias, { where });
2437
- const [row] = await this.connection.unsafe(text, params);
2438
- return Math.round(Number(row?.[alias] ?? 0));
2439
- }
2440
- async pluckNumberValues(expression, alias, options = {}) {
2441
- const { text, params } = buildProjectionQuery(this.table, expression, alias, options);
2442
- const rows = await this.connection.unsafe(text, params);
2443
- return rows.flatMap((row) => {
2444
- const value = row[alias];
2445
- return value === null || value === undefined ? [] : [Number(value)];
2446
- });
2447
- }
2448
- async countGroupedBy(column, where = {}) {
2449
- const { text, params } = buildGroupedCountQuery(this.table, column, where);
2450
- const rows = await this.connection.unsafe(text, params);
2451
- return rows.map(({ value, count }) => ({
2452
- value,
2453
- count: Number(count)
2454
- }));
2455
- }
2456
- async findByHasManyRelation(relation, parentId, options = {}) {
2457
- return await this.findWhere({
2458
- [relation.foreignKey]: parentId
2459
- }, options);
2460
- }
2461
- async loadHasManyForParents(parents, relation, options = {}) {
2462
- if (parents.length === 0) {
2463
- return indexHasManyRelation(parents, [], relation);
2464
- }
2465
- const parentIds = [...new Set(parents.map((parent) => parent[relation.localKey]))];
2466
- const children = await this.findWhere({
2467
- [relation.foreignKey]: parentIds
2468
- }, options);
2469
- return indexHasManyRelation(parents, children, relation);
2470
- }
2471
- async loadBelongsToForParents(children, relation, parentRepository, options = {}) {
2472
- if (children.length === 0) {
2473
- return new Map;
2474
- }
2475
- const ownerIds = [...new Set(children.map((child) => child[relation.foreignKey]))];
2476
- const parents = await parentRepository.withConnection(this.connection).findWhere({
2477
- [relation.ownerKey]: ownerIds
2478
- }, options);
2479
- return indexBelongsToRelation(children, parents, relation);
2480
- }
2481
- async loadMorphManyForParents(parents, relation, options = {}) {
2482
- if (parents.length === 0) {
2483
- return indexMorphManyRelation(parents, [], relation);
2484
- }
2485
- const parentIds = [...new Set(parents.map((parent) => parent[relation.localKey]))];
2486
- const children = await this.findWhere({
2487
- [relation.morphTypeKey]: relation.morphType,
2488
- [relation.morphIdKey]: parentIds
2489
- }, options);
2490
- return indexMorphManyRelation(parents, children, relation);
2491
- }
2492
- async loadMorphOneForParents(parents, relation, options = {}) {
2493
- const grouped = await this.loadMorphManyForParents(parents, relation, options);
2494
- const result = new Map;
2495
- for (const parent of parents) {
2496
- const matches = grouped.get(parent[relation.localKey]) ?? [];
2497
- result.set(parent[relation.localKey], matches[0]);
2498
- }
2499
- return result;
2500
- }
2501
- async loadMorphToForChildren(children, relation, repositoriesByType, options = {}) {
2502
- if (children.length === 0) {
2503
- return new Map;
2504
- }
2505
- const idsByType = new Map;
2506
- for (const child of children) {
2507
- const morphType = String(child[relation.morphTypeKey]);
2508
- const morphId = child[relation.morphIdKey];
2509
- const ids = idsByType.get(morphType) ?? new Set;
2510
- ids.add(morphId);
2511
- idsByType.set(morphType, ids);
2512
- }
2513
- const parentsByType = new Map;
2514
- for (const [morphType, ids] of idsByType) {
2515
- const repository = repositoriesByType.get(morphType);
2516
- if (!repository) {
2517
- continue;
2518
- }
2519
- const ownerKey = repository.getTable().primaryKey;
2520
- const parents = await repository.withConnection(this.connection).findWhere({
2521
- [ownerKey]: [...ids]
2522
- }, options);
2523
- const indexed = new Map;
2524
- for (const parent of parents) {
2525
- indexed.set(parent[ownerKey], parent);
2526
- }
2527
- parentsByType.set(morphType, indexed);
2528
- }
2529
- return indexMorphToRelation(children, parentsByType, relation);
2530
- }
2531
- }
2532
- var baseRepository_default = BaseRepository5;
2533
- // ../../src/core/database/model.ts
2534
- var modelRepositories = new WeakMap;
2535
- var modelGlobalScopes = new WeakMap;
2536
- var modelBooted = new WeakSet;
2537
- // ../../src/core/database/schema/columnDefinition.ts
2538
- class ColumnDefinition {
2539
- name;
2540
- kind;
2541
- length;
2542
- isNullable = false;
2543
- isPrimary = false;
2544
- isUnique = false;
2545
- autoIncrement = false;
2546
- defaultValue;
2547
- checkExpression;
2548
- foreignKey;
2549
- constructor(name, kind) {
2550
- this.name = name;
2551
- this.kind = kind;
2552
- }
2553
- nullable() {
2554
- this.isNullable = true;
2555
- return this;
2556
- }
2557
- notNullable() {
2558
- this.isNullable = false;
2559
- return this;
2560
- }
2561
- default(value) {
2562
- if (typeof value === "boolean") {
2563
- this.defaultValue = value ? "TRUE" : "FALSE";
2564
- return this;
2565
- }
2566
- if (typeof value === "number") {
2567
- this.defaultValue = String(value);
2568
- return this;
2569
- }
2570
- this.defaultValue = `'${value.replace(/'/g, "''")}'`;
2571
- return this;
2572
- }
2573
- defaultRaw(expression) {
2574
- this.defaultValue = expression;
2575
- return this;
2576
- }
2577
- unique() {
2578
- this.isUnique = true;
2579
- return this;
2580
- }
2581
- primary() {
2582
- this.isPrimary = true;
2583
- return this;
2584
- }
2585
- check(expression) {
2586
- this.checkExpression = expression;
2587
- return this;
2588
- }
2589
- }
2590
-
2591
- class ForeignIdColumnDefinition extends ColumnDefinition {
2592
- constructor(name) {
2593
- super(name, "foreignId");
2594
- this.notNullable();
2595
- }
2596
- references(table, column = "id") {
2597
- this.foreignKey = {
2598
- referencesTable: table,
2599
- referencesColumn: column
2600
- };
2601
- return this;
2602
- }
2603
- constrained(table) {
2604
- const referencesTable = table ?? inferReferencedTable(this.name);
2605
- return this.references(referencesTable);
2606
- }
2607
- cascadeOnDelete() {
2608
- if (!this.foreignKey) {
2609
- throw new Error(`Foreign key is not defined for column ${this.name}`);
2610
- }
2611
- this.foreignKey.onDelete = "cascade";
2612
- return this;
2613
- }
2614
- nullOnDelete() {
2615
- if (!this.foreignKey) {
2616
- throw new Error(`Foreign key is not defined for column ${this.name}`);
2617
- }
2618
- this.foreignKey.onDelete = "set null";
2619
- return this;
2620
- }
2621
- }
2622
- function inferReferencedTable(columnName) {
2623
- if (!columnName.endsWith("_id")) {
2624
- throw new Error(`Cannot infer referenced table from column ${columnName}`);
2625
- }
2626
- return columnName.slice(0, -3);
2627
- }
2628
-
2629
- // ../../src/core/database/schema/blueprint.ts
2630
- class Blueprint {
2631
- table;
2632
- action;
2633
- columns = [];
2634
- indexes = [];
2635
- droppedColumns = [];
2636
- droppedIndexes = [];
2637
- constructor(table, action) {
2638
- this.table = table;
2639
- this.action = action;
2640
- }
2641
- id(name = "id") {
2642
- const column = new ColumnDefinition(name, "id");
2643
- column.primary();
2644
- column.autoIncrement = true;
2645
- this.columns.push(column);
2646
- return column;
2647
- }
2648
- string(name, length) {
2649
- const column = new ColumnDefinition(name, "string");
2650
- column.length = length;
2651
- column.notNullable();
2652
- this.columns.push(column);
2653
- return column;
2654
- }
2655
- text(name) {
2656
- const column = new ColumnDefinition(name, "text");
2657
- column.notNullable();
2658
- this.columns.push(column);
2659
- return column;
2660
- }
2661
- boolean(name) {
2662
- const column = new ColumnDefinition(name, "boolean");
2663
- column.notNullable();
2664
- this.columns.push(column);
2665
- return column;
2666
- }
2667
- integer(name) {
2668
- const column = new ColumnDefinition(name, "integer");
2669
- column.notNullable();
2670
- this.columns.push(column);
2671
- return column;
2672
- }
2673
- bigInteger(name) {
2674
- const column = new ColumnDefinition(name, "bigInteger");
2675
- column.notNullable();
2676
- this.columns.push(column);
2677
- return column;
2678
- }
2679
- timestamp(name) {
2680
- const column = new ColumnDefinition(name, "timestamp");
2681
- column.notNullable();
2682
- this.columns.push(column);
2683
- return column;
2684
- }
2685
- json(name) {
2686
- const column = new ColumnDefinition(name, "json");
2687
- column.notNullable();
2688
- this.columns.push(column);
2689
- return column;
2690
- }
2691
- jsonb(name) {
2692
- const column = new ColumnDefinition(name, "jsonb");
2693
- column.notNullable();
2694
- this.columns.push(column);
2695
- return column;
2696
- }
2697
- foreignId(name) {
2698
- const column = new ForeignIdColumnDefinition(name);
2699
- this.columns.push(column);
2700
- return column;
2701
- }
2702
- timestamps() {
2703
- this.timestamp("created_at").defaultRaw("NOW()");
2704
- this.timestamp("updated_at").defaultRaw("NOW()");
2705
- }
2706
- softDeletes() {
2707
- this.timestamp("deleted_at").nullable();
2708
- }
2709
- dropColumn(name) {
2710
- this.droppedColumns.push(name);
2711
- }
2712
- dropSoftDeletes() {
2713
- this.dropColumn("deleted_at");
2714
- this.dropIndex(`idx_${this.table}_deleted_at`);
2715
- }
2716
- dropIndex(name) {
2717
- this.droppedIndexes.push(name);
2718
- }
2719
- unique(columns, name) {
2720
- this.indexes.push({
2721
- name,
2722
- columns: Array.isArray(columns) ? columns : [columns],
2723
- kind: "unique"
2724
- });
2725
- }
2726
- index(columns, options = {}) {
2727
- this.indexes.push({
2728
- name: options.name,
2729
- columns: Array.isArray(columns) ? columns : [columns],
2730
- kind: "index",
2731
- order: options.order
2732
- });
2733
- }
2734
- partialIndex(columns, where, nameOrOptions) {
2735
- const options = typeof nameOrOptions === "string" ? { name: nameOrOptions } : nameOrOptions ?? {};
2736
- this.indexes.push({
2737
- name: options.name,
2738
- columns: Array.isArray(columns) ? columns : [columns],
2739
- kind: options.unique ? "uniquePartial" : "partial",
2740
- where
2741
- });
2742
- }
2743
- fullText(columns, name) {
2744
- this.indexes.push({
2745
- name,
2746
- columns: Array.isArray(columns) ? columns : [columns],
2747
- kind: "fullText"
2748
- });
2749
- }
2750
- ginIndex(column, name) {
2751
- this.indexes.push({
2752
- name,
2753
- columns: [column],
2754
- kind: "gin"
2755
- });
2756
- }
2757
- }
2758
- // ../../src/core/database/schema/errors.ts
2759
- class UnsupportedSchemaFeatureError extends Error {
2760
- constructor(feature, driver) {
2761
- super(`${feature} is not supported for the ${driver} driver`);
2762
- this.name = "UnsupportedSchemaFeatureError";
2763
- }
2764
- }
2765
- // ../../src/core/database/schema/grammars/grammar.ts
2766
- function compileColumnType(driver, column) {
2767
- switch (column.kind) {
2768
- case "id":
2769
- return compileIdType(driver);
2770
- case "string":
2771
- return compileStringType(driver, column.length);
2772
- case "text":
2773
- return compileTextType(driver);
2774
- case "boolean":
2775
- return compileBooleanType(driver);
2776
- case "integer":
2777
- case "foreignId":
2778
- return compileIntegerType(driver);
2779
- case "bigInteger":
2780
- return compileBigIntegerType(driver);
2781
- case "timestamp":
2782
- return compileTimestampType(driver);
2783
- case "json":
2784
- return compileJsonType(driver);
2785
- case "jsonb":
2786
- return compileJsonbType(driver);
2787
- default:
2788
- throw new Error(`Unsupported column kind: ${column.kind}`);
2789
- }
2790
- }
2791
- function compileIdType(driver) {
2792
- switch (driver) {
2793
- case "pgsql":
2794
- return "SERIAL";
2795
- case "mysql":
2796
- return "BIGINT UNSIGNED";
2797
- case "sqlite":
2798
- return "INTEGER";
2799
- }
2800
- }
2801
- function compileStringType(driver, length) {
2802
- switch (driver) {
2803
- case "pgsql":
2804
- return "TEXT";
2805
- case "mysql":
2806
- return length ? `VARCHAR(${length})` : "VARCHAR(255)";
2807
- case "sqlite":
2808
- return "TEXT";
2809
- }
2810
- }
2811
- function compileTextType(driver) {
2812
- switch (driver) {
2813
- case "pgsql":
2814
- case "sqlite":
2815
- return "TEXT";
2816
- case "mysql":
2817
- return "TEXT";
2818
- }
2819
- }
2820
- function compileBooleanType(driver) {
2821
- switch (driver) {
2822
- case "pgsql":
2823
- return "BOOLEAN";
2824
- case "mysql":
2825
- return "BOOLEAN";
2826
- case "sqlite":
2827
- return "INTEGER";
2828
- }
2829
- }
2830
- function compileIntegerType(driver) {
2831
- switch (driver) {
2832
- case "pgsql":
2833
- return "INTEGER";
2834
- case "mysql":
2835
- return "INT";
2836
- case "sqlite":
2837
- return "INTEGER";
2838
- }
2839
- }
2840
- function compileBigIntegerType(driver) {
2841
- switch (driver) {
2842
- case "pgsql":
2843
- return "BIGINT";
2844
- case "mysql":
2845
- return "BIGINT";
2846
- case "sqlite":
2847
- return "INTEGER";
2848
- }
2849
- }
2850
- function compileTimestampType(driver) {
2851
- switch (driver) {
2852
- case "pgsql":
2853
- return "TIMESTAMPTZ";
2854
- case "mysql":
2855
- return "TIMESTAMP";
2856
- case "sqlite":
2857
- return "TEXT";
2858
- }
2859
- }
2860
- function compileJsonType(driver) {
2861
- switch (driver) {
2862
- case "pgsql":
2863
- return "JSONB";
2864
- case "mysql":
2865
- return "JSON";
2866
- case "sqlite":
2867
- return "TEXT";
2868
- }
2869
- }
2870
- function compileJsonbType(driver) {
2871
- switch (driver) {
2872
- case "pgsql":
2873
- return "JSONB";
2874
- case "mysql":
2875
- return "JSON";
2876
- case "sqlite":
2877
- return "TEXT";
2878
- }
2879
- }
2880
-
2881
- // ../../src/core/database/schema/grammars/compileStatements.ts
2882
- function compileCreateTable(driver, blueprint) {
2883
- const table = quoteIdentifier(blueprint.table);
2884
- const parts = blueprint.columns.map((column) => compileColumn(driver, column, "create"));
2885
- for (const index of blueprint.indexes) {
2886
- if (index.kind === "unique" && index.columns.length > 1) {
2887
- const columns = index.columns.map((column) => quoteIdentifier(column)).join(", ");
2888
- parts.push(`UNIQUE (${columns})`);
2889
- }
2890
- }
2891
- const statements = [`CREATE TABLE IF NOT EXISTS ${table} (
2892
- ${parts.join(`,
2893
- `)}
2894
- )`];
2895
- for (const index of blueprint.indexes) {
2896
- if (index.kind === "unique" && index.columns.length === 1) {
2897
- continue;
2898
- }
2899
- if (index.kind === "index") {
2900
- statements.push(compileIndex(driver, blueprint.table, index));
2901
- } else if (index.kind === "partial" || index.kind === "uniquePartial" || index.kind === "gin" || index.kind === "fullText") {
2902
- statements.push(...compileSpecialIndex(driver, blueprint.table, index));
2903
- }
2904
- }
2905
- return statements;
2906
- }
2907
- function compileAlterTable(driver, blueprint) {
2908
- const statements = [];
2909
- const table = quoteIdentifier(blueprint.table);
2910
- for (const column of blueprint.columns) {
2911
- const addPrefix = driver === "pgsql" ? "ADD COLUMN IF NOT EXISTS" : "ADD COLUMN";
2912
- statements.push(`ALTER TABLE ${table}
2913
- ${addPrefix} ${compileColumn(driver, column, "alter")}`);
2914
- }
2915
- for (const columnName of blueprint.droppedColumns) {
2916
- const dropPrefix = driver === "pgsql" ? "DROP COLUMN IF EXISTS" : "DROP COLUMN";
2917
- statements.push(`ALTER TABLE ${table} ${dropPrefix} ${quoteIdentifier(columnName)}`);
2918
- }
2919
- for (const indexName of blueprint.droppedIndexes) {
2920
- statements.push(`DROP INDEX IF EXISTS ${quoteIdentifier(indexName)}`);
2921
- }
2922
- for (const index of blueprint.indexes) {
2923
- if (index.kind === "index" || index.kind === "unique") {
2924
- statements.push(compileIndex(driver, blueprint.table, index));
2925
- } else {
2926
- statements.push(...compileSpecialIndex(driver, blueprint.table, index));
2927
- }
2928
- }
2929
- return statements;
2930
- }
2931
- function compileDropTable(driver, tableName) {
2932
- const cascade = driver === "pgsql" ? " CASCADE" : "";
2933
- return [`DROP TABLE IF EXISTS ${quoteIdentifier(tableName)}${cascade}`];
2934
- }
2935
- function compileColumn(driver, column, mode) {
2936
- const parts = [quoteIdentifier(column.name), compileColumnType(driver, column)];
2937
- if (column.autoIncrement && driver === "mysql") {
2938
- parts[1] = `${parts[1]} AUTO_INCREMENT`;
2939
- }
2940
- if (column.isPrimary && mode === "create") {
2941
- if (driver === "sqlite") {
2942
- parts.push("PRIMARY KEY AUTOINCREMENT");
2943
- } else {
2944
- parts.push("PRIMARY KEY");
2945
- }
2946
- } else if (!column.isNullable) {
2947
- parts.push("NOT NULL");
2948
- } else if (column.isNullable) {
2949
- parts.push("NULL");
2950
- }
2951
- if (column.defaultValue !== undefined) {
2952
- parts.push(`DEFAULT ${column.defaultValue}`);
2953
- }
2954
- if (column.isUnique) {
2955
- parts.push("UNIQUE");
2956
- }
2957
- if (column.checkExpression) {
2958
- parts.push(`CHECK (${column.checkExpression})`);
2959
- }
2960
- if (column.foreignKey) {
2961
- const { referencesTable, referencesColumn, onDelete } = column.foreignKey;
2962
- const reference = `${quoteIdentifier(referencesTable)}(${quoteIdentifier(referencesColumn)})`;
2963
- let clause = `REFERENCES ${reference}`;
2964
- if (onDelete === "cascade") {
2965
- clause += " ON DELETE CASCADE";
2966
- } else if (onDelete === "set null") {
2967
- clause += " ON DELETE SET NULL";
2968
- }
2969
- parts.push(clause);
2970
- }
2971
- return parts.join(" ");
2972
- }
2973
- function compileIndex(_driver, tableName, index) {
2974
- const indexName = index.name ?? defaultIndexName(tableName, index.columns, index.kind === "unique" ? "unique" : "index");
2975
- const columns = index.columns.map((column) => {
2976
- const quoted = quoteIdentifier(column);
2977
- if (index.order === "desc") {
2978
- return `${quoted} DESC`;
2979
- }
2980
- return quoted;
2981
- }).join(", ");
2982
- const unique = index.kind === "unique" ? "UNIQUE " : "";
2983
- return `CREATE ${unique}INDEX IF NOT EXISTS ${quoteIdentifier(indexName)} ON ${quoteIdentifier(tableName)}(${columns})`;
2984
- }
2985
- function compileSpecialIndex(driver, tableName, index) {
2986
- const indexName = index.name ?? defaultIndexName(tableName, index.columns, index.kind);
2987
- const columns = index.columns.map((column) => quoteIdentifier(column)).join(", ");
2988
- switch (index.kind) {
2989
- case "partial":
2990
- case "uniquePartial": {
2991
- if (driver !== "pgsql") {
2992
- throw new UnsupportedSchemaFeatureError("partialIndex()", driver);
2993
- }
2994
- const unique = index.kind === "uniquePartial" ? "UNIQUE " : "";
2995
- return [
2996
- `CREATE ${unique}INDEX IF NOT EXISTS ${quoteIdentifier(indexName)} ON ${quoteIdentifier(tableName)}(${columns}) WHERE ${index.where}`
2997
- ];
2998
- }
2999
- case "gin": {
3000
- if (driver !== "pgsql") {
3001
- throw new UnsupportedSchemaFeatureError("ginIndex()", driver);
3002
- }
3003
- return [
3004
- `CREATE INDEX IF NOT EXISTS ${quoteIdentifier(indexName)} ON ${quoteIdentifier(tableName)} USING GIN(${columns})`
3005
- ];
3006
- }
3007
- case "fullText": {
3008
- if (driver === "mysql") {
3009
- return [
3010
- `CREATE FULLTEXT INDEX ${quoteIdentifier(indexName)} ON ${quoteIdentifier(tableName)}(${columns})`
3011
- ];
3012
- }
3013
- if (driver === "pgsql") {
3014
- throw new UnsupportedSchemaFeatureError("fullText(); use ginIndex() with a tsvector column on PostgreSQL", driver);
3015
- }
3016
- throw new UnsupportedSchemaFeatureError("fullText()", driver);
3017
- }
3018
- default:
3019
- return [];
3020
- }
3021
- }
3022
- function defaultIndexName(tableName, columns, kind) {
3023
- return `idx_${tableName}_${columns.join("_")}_${kind}`;
3024
- }
3025
- function compileBlueprint(driver, blueprint) {
3026
- switch (blueprint.action) {
3027
- case "create":
3028
- return compileCreateTable(driver, blueprint);
3029
- case "alter":
3030
- return compileAlterTable(driver, blueprint);
3031
- case "drop":
3032
- return compileDropTable(driver, blueprint.table);
3033
- default:
3034
- throw new Error(`Unsupported blueprint action: ${blueprint.action}`);
3035
- }
3036
- }
3037
- // ../../src/core/database/schema/grammars/createGrammar.ts
3038
- function createGrammar(driver) {
3039
- return {
3040
- driver,
3041
- compile(blueprint) {
3042
- return compileBlueprint(driver, blueprint);
3043
- }
3044
- };
3045
- }
3046
-
3047
- // ../../src/core/database/schema/grammars/mysqlGrammar.ts
3048
- var MySqlGrammar = createGrammar("mysql");
3049
-
3050
- // ../../src/core/database/schema/grammars/postgresGrammar.ts
3051
- var PostgresGrammar = createGrammar("pgsql");
3052
-
3053
- // ../../src/core/database/schema/grammars/sqliteGrammar.ts
3054
- var SqliteGrammar = createGrammar("sqlite");
3055
-
3056
- // ../../src/core/database/schema/grammars/index.ts
3057
- function grammarForDriver(driver) {
3058
- switch (driver) {
3059
- case "pgsql":
3060
- return PostgresGrammar;
3061
- case "mysql":
3062
- return MySqlGrammar;
3063
- case "sqlite":
3064
- return SqliteGrammar;
3065
- default:
3066
- throw new Error(`Unsupported database driver: ${driver}`);
3067
- }
3068
- }
3069
- // ../../src/core/database/schema/schema.ts
3070
- class SchemaBuilder {
3071
- #driver;
3072
- #statements = [];
3073
- constructor(driver) {
3074
- this.#driver = driver;
3075
- }
3076
- create(table, callback) {
3077
- const blueprint = new Blueprint(table, "create");
3078
- callback(blueprint);
3079
- this.#statements.push(...grammarForDriver(this.#driver).compile(blueprint));
3080
- return this;
3081
- }
3082
- table(table, callback) {
3083
- const blueprint = new Blueprint(table, "alter");
3084
- callback(blueprint);
3085
- this.#statements.push(...grammarForDriver(this.#driver).compile(blueprint));
3086
- return this;
3087
- }
3088
- drop(table) {
3089
- const blueprint = new Blueprint(table, "drop");
3090
- this.#statements.push(...grammarForDriver(this.#driver).compile(blueprint));
3091
- return this;
3092
- }
3093
- toSql() {
3094
- return [...this.#statements];
3095
- }
3096
- async execute(db2) {
3097
- for (const statement of this.#statements) {
3098
- await db2.unsafe(statement);
3099
- }
3100
- }
3101
- }
3102
- // ../../src/core/database/table.ts
3103
- function defineTable5(definition) {
3104
- return definition;
3105
- }
3106
- // ../../src/core/queue/failedJobTable.ts
3107
- var failedJobTable = defineTable5({
3108
- name: "failed_job",
3109
- primaryKey: "id",
3110
- columns: ["id", "job_name", "payload", "exception", "failed_at"],
3111
- defaultOrderBy: { column: "failed_at", direction: "DESC" }
3112
- });
3113
-
3114
- // ../../src/core/queue/failedJobRepository.ts
3115
- class FailedJobRepository extends baseRepository_default {
3116
- constructor() {
3117
- super(failedJobTable);
3118
- }
3119
- }
3120
- var failedJobRepository_default = FailedJobRepository;
3121
-
3122
- // ../../src/core/queue/failedJobService.ts
3123
- class FailedJobService {
3124
- repository;
3125
- constructor(repository) {
3126
- this.repository = repository;
3127
- }
3128
- async recordFailure(input) {
3129
- return await this.repository.create({
3130
- job_name: input.jobName,
3131
- payload: input.payload,
3132
- exception: input.exception,
3133
- failed_at: new Date
3134
- });
3135
- }
3136
- listRecent(limit = 50) {
3137
- return this.repository.findAll({
3138
- limit,
3139
- orderBy: { column: "failed_at", direction: "DESC" }
3140
- });
3141
- }
3142
- async retry(id) {
3143
- const failedJob = await this.repository.findByIdOrThrow(id, (jobId) => new Error(`Failed job ${jobId} not found.`));
3144
- await this.repository.deleteById(id);
3145
- return failedJob;
3146
- }
3147
- async delete(id) {
3148
- const deleted = await this.repository.deleteById(id);
3149
- if (!deleted) {
3150
- throw new Error(`Failed job ${id} not found.`);
3151
- }
3152
- }
3153
- async flush() {
3154
- const jobs = await this.repository.findAll();
3155
- let deleted = 0;
3156
- for (const job of jobs) {
3157
- if (await this.repository.deleteById(job.id)) {
3158
- deleted += 1;
3159
- }
3160
- }
3161
- return deleted;
3162
- }
3163
- }
3164
- var failedJobService_default = FailedJobService;
3165
-
3166
- // ../../src/core/queue/jobRegistry.ts
3167
- class JobRegistry {
3168
- factories = new Map;
3169
- instances = new WeakMap;
3170
- register(name, factory) {
3171
- this.factories.set(name, factory);
3172
- }
3173
- resolveName(job) {
3174
- return this.instances.get(job);
3175
- }
3176
- track(name, job) {
3177
- this.instances.set(job, name);
3178
- return job;
3179
- }
3180
- create(name) {
3181
- const factory = this.factories.get(name);
3182
- if (!factory) {
3183
- return;
3184
- }
3185
- return factory();
3186
- }
3187
- names() {
3188
- return [...this.factories.keys()];
3189
- }
3190
- }
3191
- var JOB_REGISTRY_KEY = Symbol.for("@getstrata/jobRegistry");
3192
- function readSharedJobRegistry() {
3193
- const globalRegistry = globalThis[JOB_REGISTRY_KEY];
3194
- if (globalRegistry) {
3195
- return globalRegistry;
3196
- }
3197
- const registry = new JobRegistry;
3198
- globalThis[JOB_REGISTRY_KEY] = registry;
3199
- return registry;
3200
- }
3201
- var jobRegistry = readSharedJobRegistry();
3202
-
3203
- // ../../src/core/queue/jobRunner.ts
3204
- async function runQueueJob(envelope, failedJobs) {
3205
- const job = jobRegistry.create(envelope.name);
3206
- if (!job) {
3207
- throw new Error(`Unknown job "${envelope.name}".`);
3208
- }
3209
- const attempts = envelope.attempts ?? 0;
3210
- try {
3211
- await job.handle(envelope.payload);
3212
- } catch (error) {
3213
- const nextAttempt = attempts + 1;
3214
- const maxAttempts = job.maxAttempts ?? queueConfig.maxAttempts;
3215
- if (nextAttempt < maxAttempts) {
3216
- const backoffMs = job.backoffMs ?? queueConfig.backoffMs;
3217
- await new Promise((resolve) => setTimeout(resolve, backoffMs * nextAttempt));
3218
- await runQueueJob({
3219
- ...envelope,
3220
- attempts: nextAttempt
3221
- }, failedJobs);
3222
- return;
3223
- }
3224
- await failedJobs.recordFailure({
3225
- jobName: envelope.name,
3226
- payload: envelope.payload,
3227
- exception: error instanceof Error ? error.stack ?? error.message : String(error)
3228
- });
3229
- throw error;
3230
- }
3231
- }
3232
-
3233
- // ../../src/core/queue/redisQueue.ts
3234
- var {RedisClient: RedisClient2 } = globalThis.Bun;
3235
- var QUEUE_LIST_KEY = "workhub:queue:default";
3236
- var QUEUE_HIGH_KEY = "workhub:queue:high";
3237
- var QUEUE_LOW_KEY = "workhub:queue:low";
3238
- function queueKeyForPriority(priority = "default") {
3239
- switch (priority) {
3240
- case "high":
3241
- return QUEUE_HIGH_KEY;
3242
- case "low":
3243
- return QUEUE_LOW_KEY;
3244
- default:
3245
- return QUEUE_LIST_KEY;
3246
- }
3247
- }
3248
- class RedisQueue {
3249
- client;
3250
- constructor(redisUrl) {
3251
- this.client = new RedisClient2(redisUrl);
3252
- }
3253
- async dispatch(job, payload) {
3254
- const name = jobRegistry.resolveName(job);
3255
- if (!name) {
3256
- throw new Error("Job is not registered with the queue worker registry.");
3257
- }
3258
- const envelope = {
3259
- name,
3260
- payload,
3261
- attempts: 0
3262
- };
3263
- const queueKey = queueKeyForPriority(job.priority);
3264
- await this.client.lpush(queueKey, JSON.stringify(envelope));
3265
- }
3266
- }
3267
-
3268
- // ../../src/core/queue/resilientQueue.ts
3269
- class ResilientQueue {
3270
- failedJobs;
3271
- asyncDispatch;
3272
- constructor(failedJobs, asyncDispatch = false) {
3273
- this.failedJobs = failedJobs;
3274
- this.asyncDispatch = asyncDispatch;
3275
- }
3276
- async dispatch(job, payload) {
3277
- const name = jobRegistry.resolveName(job);
3278
- if (!name) {
3279
- throw new Error("Job is not registered with the queue worker registry.");
3280
- }
3281
- const envelope = {
3282
- name,
3283
- payload,
3284
- attempts: 0
3285
- };
3286
- if (this.asyncDispatch) {
3287
- setTimeout(() => {
3288
- runQueueJob(envelope, this.failedJobs).catch((error) => {
3289
- console.error("[ResilientQueue] Job failed:", error);
3290
- });
3291
- }, 0);
3292
- return;
3293
- }
3294
- await runQueueJob(envelope, this.failedJobs);
3295
- }
3296
- }
3297
-
3298
- // ../../src/core/queue/publicQueue.ts
3299
- function createFailedJobService() {
3300
- return new failedJobService_default(new failedJobRepository_default);
3301
- }
3302
- function createTrackedJob(name, job) {
3303
- return jobRegistry.track(name, job);
3304
- }
3305
- function createProductionQueue(driver, options = {}) {
3306
- options.registerJobs?.();
3307
- const failedJobs = options.failedJobs ?? createFailedJobService();
3308
- if (driver === "redis") {
3309
- if (!options.redisUrl) {
3310
- throw new Error('QUEUE_DRIVER="redis" requires REDIS_URL to be set.');
3311
- }
3312
- return new RedisQueue(options.redisUrl);
3313
- }
3314
- return new ResilientQueue(failedJobs, driver === "async");
3315
- }
3316
-
3317
- // ../../src/core/queue/createAppQueue.ts
3318
- var FAILED_JOB_SERVICE_TOKEN = "core.failedJobs";
3319
- function createAppQueue(driver, redisUrl, failedJobs = createFailedJobService(), registerJobs) {
3320
- return createProductionQueue(driver, {
3321
- redisUrl,
3322
- failedJobs,
3323
- registerJobs
3324
- });
3325
- }
3326
-
3327
- // ../../src/bootstrap/cache/modelCacheTags.ts
3328
- function cacheTagsForModelWrite(tableName, action) {
3329
- const module = discoverModules().find((entry) => entry.tableName === tableName);
3330
- const baseTags = module?.cacheTags ?? [`${tableName}s`];
3331
- const isDelete = action === "deleted" || action === "force-deleted";
3332
- const extraTags = isDelete ? module?.cacheDeleteExtraTags ?? [] : [];
3333
- return [...new Set([...baseTags, ...extraTags])];
3334
- }
3335
- function discoverModelTableNames() {
3336
- return discoverModules().map((module) => module.tableName).filter((tableName) => tableName !== undefined);
3337
- }
3338
-
3339
- // ../../src/bootstrap/listeners/invalidateCacheOnModelWrite.ts
3340
- var MODEL_WRITE_ACTIONS = ["created", "updated", "deleted", "restored", "force-deleted"];
3341
- function registerInvalidateCacheOnModelWriteListeners(bus = eventBus) {
3342
- for (const tableName of discoverModelTableNames()) {
3343
- for (const action of MODEL_WRITE_ACTIONS) {
3344
- bus.listen(modelEventName(tableName, action), async () => {
3345
- const tags = cacheTagsForModelWrite(tableName, action);
3346
- if (tags.length === 0) {
3347
- return;
3348
- }
3349
- let cache;
3350
- let queue;
3351
- try {
3352
- cache = resolveApplicationCache();
3353
- queue = resolveApplicationQueue();
3354
- } catch {
3355
- return;
3356
- }
3357
- const job = createTrackedJob("cache.invalidate-tags", new invalidateCacheTagsJob_default(cache));
3358
- await queue.dispatch(job, { tags });
3359
- });
3360
- }
881
+ // ../../src/bootstrap/listeners/invalidateCacheOnModelWrite.ts
882
+ var MODEL_WRITE_ACTIONS = ["created", "updated", "deleted", "restored", "force-deleted"];
883
+ function registerInvalidateCacheOnModelWriteListeners(bus = eventBus2) {
884
+ for (const tableName of discoverModelTableNames()) {
885
+ for (const action of MODEL_WRITE_ACTIONS) {
886
+ bus.listen(modelEventName(tableName, action), async () => {
887
+ const tags = cacheTagsForModelWrite(tableName, action);
888
+ if (tags.length === 0) {
889
+ return;
890
+ }
891
+ let cache;
892
+ let queue;
893
+ try {
894
+ cache = resolveApplicationCache();
895
+ queue = resolveApplicationQueue();
896
+ } catch {
897
+ return;
898
+ }
899
+ const job = createTrackedJob("cache.invalidate-tags", new InvalidateCacheTagsJob(cache));
900
+ await queue.dispatch(job, { tags });
901
+ });
902
+ }
3361
903
  }
3362
904
  }
3363
905
 
@@ -3383,46 +925,8 @@ var listenersProvider = {
3383
925
  };
3384
926
  var listeners_default = listenersProvider;
3385
927
 
3386
- // ../../src/core/auth/policy.ts
3387
- var BLOCKED_POLICY_ACTIONS = new Set([
3388
- "constructor",
3389
- "toString",
3390
- "valueOf",
3391
- "hasOwnProperty",
3392
- "isPrototypeOf",
3393
- "propertyIsEnumerable",
3394
- "__proto__"
3395
- ]);
3396
-
3397
- class PolicyGate {
3398
- constructor() {}
3399
- policies = new Map;
3400
- register(resource, policy) {
3401
- this.policies.set(resource, policy);
3402
- }
3403
- allows(resource, action, user, model) {
3404
- const policy = this.policies.get(resource);
3405
- if (!policy) {
3406
- return false;
3407
- }
3408
- if (BLOCKED_POLICY_ACTIONS.has(action) || !(action in policy)) {
3409
- return false;
3410
- }
3411
- const handler = policy[action];
3412
- if (typeof handler !== "function") {
3413
- return false;
3414
- }
3415
- const resolvedUser = user === undefined ? currentAuthUser() : user;
3416
- return model === undefined ? handler.call(policy, resolvedUser) : handler.call(policy, resolvedUser, model);
3417
- }
3418
- authorize(resource, action, user, model) {
3419
- if (!this.allows(resource, action, user, model)) {
3420
- throw new ForbiddenError2;
3421
- }
3422
- }
3423
- }
3424
-
3425
928
  // ../../src/bootstrap/providers/policy.ts
929
+ import { PolicyGate } from "@getstrata/core/auth/policy";
3426
930
  var policyProvider = {
3427
931
  name: "core.policy",
3428
932
  register({ container }) {
@@ -3431,278 +935,23 @@ var policyProvider = {
3431
935
  };
3432
936
  var policy_default = policyProvider;
3433
937
 
3434
- // ../../src/core/jobs/dispatchWebhookJob.ts
3435
- import { createHmac as createHmac2 } from "crypto";
3436
-
3437
- // ../../src/core/security/safeUrl.ts
3438
- import { lookup as dnsLookupImpl } from "dns/promises";
3439
- var dnsLookup = dnsLookupImpl;
3440
- var BLOCKED_HOSTNAMES = new Set([
3441
- "localhost",
3442
- "127.0.0.1",
3443
- "0.0.0.0",
3444
- "::1",
3445
- "metadata.google.internal"
3446
- ]);
3447
- function isPrivateIpv4(hostname) {
3448
- const match = /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/.exec(hostname);
3449
- if (!match) {
3450
- return false;
3451
- }
3452
- const octets = match.slice(1, 5).map((part) => Number.parseInt(part, 10));
3453
- if (octets.some((octet) => octet < 0 || octet > 255)) {
3454
- return true;
3455
- }
3456
- const [a = 0, b = 0] = octets;
3457
- if (a === 10) {
3458
- return true;
3459
- }
3460
- if (a === 127) {
3461
- return true;
3462
- }
3463
- if (a === 0) {
3464
- return true;
3465
- }
3466
- if (a === 169 && b === 254) {
3467
- return true;
3468
- }
3469
- if (a === 172 && b >= 16 && b <= 31) {
3470
- return true;
3471
- }
3472
- if (a === 192 && b === 168) {
3473
- return true;
3474
- }
3475
- return false;
3476
- }
3477
- function isBlockedHostname(hostname) {
3478
- const normalized = hostname.trim().toLowerCase();
3479
- if (normalized.length === 0) {
3480
- return true;
3481
- }
3482
- if (BLOCKED_HOSTNAMES.has(normalized)) {
3483
- return true;
3484
- }
3485
- if (normalized.endsWith(".local") || normalized.endsWith(".internal")) {
3486
- return true;
3487
- }
3488
- if (normalized.includes(":")) {
3489
- return true;
3490
- }
3491
- return isPrivateIpv4(normalized);
3492
- }
3493
- function assertSafeOutboundUrl(rawUrl, options = {}) {
3494
- let parsed;
3495
- try {
3496
- parsed = new URL(rawUrl);
3497
- } catch {
3498
- throw new BadRequestError("Webhook URL is invalid.");
3499
- }
3500
- if (parsed.protocol !== "https:" && !(options.allowHttp && parsed.protocol === "http:")) {
3501
- throw new BadRequestError("Webhook URL must use HTTPS.");
3502
- }
3503
- if (parsed.username || parsed.password) {
3504
- throw new BadRequestError("Webhook URL must not include credentials.");
3505
- }
3506
- if (isBlockedHostname(parsed.hostname)) {
3507
- throw new BadRequestError("Webhook URL targets a blocked host.");
3508
- }
3509
- return parsed;
3510
- }
3511
- function isBlockedIpAddress(address) {
3512
- return isBlockedHostname(address.trim().toLowerCase());
3513
- }
3514
- async function assertSafeOutboundUrlResolved(rawUrl, options = {}) {
3515
- const parsed = assertSafeOutboundUrl(rawUrl, options);
3516
- if (options.resolveDns === false) {
3517
- return parsed;
3518
- }
3519
- const hostname = parsed.hostname.trim().toLowerCase();
3520
- const results = await dnsLookup(hostname, { all: true, verbatim: true });
3521
- if (results.some((result) => isBlockedIpAddress(result.address))) {
3522
- throw new BadRequestError("Webhook URL targets a blocked host.");
3523
- }
3524
- return parsed;
3525
- }
3526
-
3527
- // ../../src/core/security/safeFetch.ts
3528
- var DEFAULT_FETCH_TIMEOUT_MS = 1e4;
3529
- async function safeFetch(input, init = {}, options = {}) {
3530
- const timeoutMs = options.timeoutMs ?? DEFAULT_FETCH_TIMEOUT_MS;
3531
- const maxRedirects = options.maxRedirects ?? 0;
3532
- const resolveDns = options.resolveDns ?? appConfig.env === "production";
3533
- const urlOptions = { allowHttp: options.allowHttp, resolveDns };
3534
- const controller = new AbortController;
3535
- const timeout = setTimeout(() => controller.abort(), timeoutMs);
3536
- try {
3537
- let currentUrl = (await assertSafeOutboundUrlResolved(input, urlOptions)).toString();
3538
- let redirectCount = 0;
3539
- while (true) {
3540
- const response = await fetch(currentUrl, {
3541
- ...init,
3542
- signal: controller.signal,
3543
- redirect: "manual"
3544
- });
3545
- if (response.status >= 300 && response.status < 400) {
3546
- const location = response.headers.get("location");
3547
- if (!location || redirectCount >= maxRedirects) {
3548
- return response;
3549
- }
3550
- currentUrl = (await assertSafeOutboundUrlResolved(new URL(location, currentUrl).toString(), urlOptions)).toString();
3551
- redirectCount += 1;
3552
- continue;
3553
- }
3554
- return response;
3555
- }
3556
- } finally {
3557
- clearTimeout(timeout);
3558
- }
3559
- }
3560
-
3561
- // ../../src/core/jobs/dispatchWebhookJob.ts
3562
- class DispatchWebhookJob extends Job {
3563
- maxAttempts = 3;
3564
- backoffMs = 2000;
3565
- async handle(payload) {
3566
- const rows = await repositoryConnection`
3567
- SELECT id, url, secret
3568
- FROM webhook
3569
- WHERE id = ${payload.webhookId} AND active = TRUE
3570
- LIMIT 1
3571
- `;
3572
- const webhook = rows[0];
3573
- if (!webhook) {
3574
- return;
3575
- }
3576
- const body = JSON.stringify({ event: payload.event, payload: payload.payload });
3577
- const signature = createHmac2("sha256", webhook.secret).update(body).digest("hex");
3578
- assertSafeOutboundUrl(webhook.url, { allowHttp: appConfig.env !== "production" });
3579
- let responseStatus = null;
3580
- let errorMessage = null;
3581
- try {
3582
- const response = await safeFetch(webhook.url, {
3583
- method: "POST",
3584
- headers: {
3585
- "content-type": "application/json",
3586
- "x-workhub-signature": signature
3587
- },
3588
- body
3589
- }, { allowHttp: appConfig.env !== "production" });
3590
- responseStatus = response.status;
3591
- if (!response.ok) {
3592
- throw new Error(`Webhook delivery failed with status ${response.status}.`);
3593
- }
3594
- } catch (error) {
3595
- errorMessage = error instanceof Error ? error.message : String(error);
3596
- await repositoryConnection`
3597
- INSERT INTO webhook_delivery (webhook_id, event, payload, response_status, error)
3598
- VALUES (
3599
- ${webhook.id},
3600
- ${payload.event},
3601
- ${JSON.stringify(payload.payload)}::jsonb,
3602
- ${responseStatus},
3603
- ${errorMessage}
3604
- )
3605
- `;
3606
- throw error instanceof Error ? error : new Error(errorMessage);
3607
- }
3608
- await repositoryConnection`
3609
- INSERT INTO webhook_delivery (webhook_id, event, payload, response_status)
3610
- VALUES (
3611
- ${webhook.id},
3612
- ${payload.event},
3613
- ${JSON.stringify(payload.payload)}::jsonb,
3614
- ${responseStatus}
3615
- )
3616
- `;
3617
- }
3618
- }
3619
- var dispatchWebhookJob_default = DispatchWebhookJob;
3620
-
3621
- // ../../src/core/contracts/di.ts
3622
- function getRequiredDependency2(dependencies, key) {
3623
- const dependency = dependencies[key];
3624
- if (dependency === undefined) {
3625
- throw new Error(`Required dependency "${key}" is not registered.`);
3626
- }
3627
- return dependency;
3628
- }
3629
-
3630
- // ../../src/core/contracts/serviceTokens.ts
3631
- var CORE_POLICY_GATE_TOKEN2 = "core.policyGate";
3632
- var CORE_AUTH_TOKEN2 = "core.auth";
3633
-
3634
- // ../../src/core/logging/logger.ts
3635
- class Logger {
3636
- channel;
3637
- constructor(channel = "app") {
3638
- this.channel = channel;
3639
- }
3640
- write(level, message, context = {}) {
3641
- const entry = {
3642
- level,
3643
- channel: this.channel,
3644
- message,
3645
- timestamp: new Date().toISOString(),
3646
- ...context
3647
- };
3648
- const line = JSON.stringify(entry);
3649
- if (level === "error") {
3650
- console.error(line);
3651
- return;
3652
- }
3653
- console.log(line);
3654
- }
3655
- debug(message, context) {
3656
- this.write("debug", message, context);
3657
- }
3658
- info(message, context) {
3659
- this.write("info", message, context);
3660
- }
3661
- warn(message, context) {
3662
- this.write("warn", message, context);
3663
- }
3664
- error(message, context) {
3665
- this.write("error", message, context);
3666
- }
3667
- }
3668
- var appLogger = new Logger("app");
3669
-
3670
- // ../../src/core/runtime/applicationRegistry.ts
3671
- var APPLICATION_CONTEXT_KEY = Symbol.for("@getstrata/applicationContext");
3672
- var activeContext;
3673
- function readStoredApplicationContext() {
3674
- if (activeContext) {
3675
- return activeContext;
3676
- }
3677
- const globalContext = globalThis[APPLICATION_CONTEXT_KEY];
3678
- if (globalContext) {
3679
- activeContext = globalContext;
3680
- }
3681
- return activeContext;
3682
- }
3683
- function requireActiveApplicationContext() {
3684
- const context = readStoredApplicationContext();
3685
- if (!context) {
3686
- throw new Error("The application context has not been bootstrapped.");
3687
- }
3688
- return context;
3689
- }
3690
- function resolveApplicationCache2() {
3691
- return getRequiredDependency2(requireActiveApplicationContext().dependencies, "cache");
3692
- }
3693
- function resolveApplicationAuth2() {
3694
- return requireActiveApplicationContext().container.resolve(CORE_AUTH_TOKEN2);
3695
- }
3696
- function resolveApplicationPolicyGate2() {
3697
- return requireActiveApplicationContext().container.resolve(CORE_POLICY_GATE_TOKEN2);
3698
- }
938
+ // ../../src/bootstrap/providers/queue.ts
939
+ import {
940
+ createAppQueue,
941
+ createFailedJobService,
942
+ FAILED_JOB_SERVICE_TOKEN
943
+ } from "@getstrata/core/queue/createAppQueue";
3699
944
 
3700
945
  // ../../src/bootstrap/queue/defaultJobs.ts
946
+ import DispatchWebhookJob from "@getstrata/core/jobs/dispatchWebhookJob";
947
+ import InvalidateCacheTagsJob2 from "@getstrata/core/jobs/invalidateCacheTagsJob";
948
+ import { jobRegistry } from "@getstrata/core/queue/jobRegistry";
949
+ import { resolveApplicationCache as resolveApplicationCache2 } from "@getstrata/core/runtime/applicationRegistry";
3701
950
  function registerDefaultJobs() {
3702
951
  jobRegistry.register("cache.invalidate-tags", () => {
3703
- return new invalidateCacheTagsJob_default(resolveApplicationCache2());
952
+ return new InvalidateCacheTagsJob2(resolveApplicationCache2());
3704
953
  });
3705
- jobRegistry.register("webhook.dispatch", () => new dispatchWebhookJob_default);
954
+ jobRegistry.register("webhook.dispatch", () => new DispatchWebhookJob);
3706
955
  }
3707
956
 
3708
957
  // ../../src/bootstrap/providers/queue.ts
@@ -3719,120 +968,8 @@ var queueProvider = {
3719
968
  };
3720
969
  var queue_default = queueProvider;
3721
970
 
3722
- // ../../src/core/storage/storage.ts
3723
- import { mkdir, readFile, unlink, writeFile } from "fs/promises";
3724
- import { dirname, join as join3 } from "path";
3725
- var {S3Client } = globalThis.Bun;
3726
-
3727
- class LocalStorageDriver {
3728
- rootDirectory;
3729
- constructor(rootDirectory) {
3730
- this.rootDirectory = rootDirectory;
3731
- }
3732
- resolveRootDirectory() {
3733
- return this.rootDirectory ?? process.env.STORAGE_PATH ?? "storage";
3734
- }
3735
- resolvePath(path) {
3736
- return join3(this.resolveRootDirectory(), path.replace(/^\/+/, ""));
3737
- }
3738
- async put(path, contents) {
3739
- const absolutePath = this.resolvePath(path);
3740
- await mkdir(dirname(absolutePath), { recursive: true });
3741
- await writeFile(absolutePath, contents);
3742
- return path;
3743
- }
3744
- async get(path) {
3745
- try {
3746
- return await readFile(this.resolvePath(path));
3747
- } catch {
3748
- return null;
3749
- }
3750
- }
3751
- async delete(path) {
3752
- try {
3753
- await unlink(this.resolvePath(path));
3754
- return true;
3755
- } catch {
3756
- return false;
3757
- }
3758
- }
3759
- }
3760
-
3761
- class S3StorageDriver {
3762
- client;
3763
- constructor(client) {
3764
- this.client = client;
3765
- }
3766
- async put(path, contents) {
3767
- await this.client.write(path.replace(/^\/+/, ""), contents);
3768
- return path;
3769
- }
3770
- async get(path) {
3771
- const normalizedPath = path.replace(/^\/+/, "");
3772
- const file = this.client.file(normalizedPath);
3773
- if (!await file.exists()) {
3774
- return null;
3775
- }
3776
- return new Uint8Array(await file.arrayBuffer());
3777
- }
3778
- async delete(path) {
3779
- try {
3780
- await this.client.unlink(path.replace(/^\/+/, ""));
3781
- return true;
3782
- } catch {
3783
- return false;
3784
- }
3785
- }
3786
- }
3787
-
3788
- class StorageManager {
3789
- driver;
3790
- constructor(driver) {
3791
- this.driver = driver;
3792
- }
3793
- put(path, contents) {
3794
- return this.driver.put(path, contents);
3795
- }
3796
- get(path) {
3797
- return this.driver.get(path);
3798
- }
3799
- delete(path) {
3800
- return this.driver.delete(path);
3801
- }
3802
- }
3803
- function resolveS3Config() {
3804
- const accessKeyId = process.env.AWS_ACCESS_KEY_ID?.trim();
3805
- const secretAccessKey = process.env.AWS_SECRET_ACCESS_KEY?.trim();
3806
- const bucket = process.env.AWS_BUCKET?.trim();
3807
- if (!accessKeyId || !secretAccessKey || !bucket) {
3808
- throw new Error('STORAGE_DRIVER="s3" requires AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, and AWS_BUCKET.');
3809
- }
3810
- return {
3811
- accessKeyId,
3812
- secretAccessKey,
3813
- bucket,
3814
- ...process.env.AWS_REGION?.trim() ? { region: process.env.AWS_REGION.trim() } : {},
3815
- ...process.env.AWS_ENDPOINT?.trim() ? { endpoint: process.env.AWS_ENDPOINT.trim() } : {}
3816
- };
3817
- }
3818
- function createS3Client(config = resolveS3Config()) {
3819
- return new S3Client({
3820
- accessKeyId: config.accessKeyId,
3821
- secretAccessKey: config.secretAccessKey,
3822
- bucket: config.bucket,
3823
- ...config.region ? { region: config.region } : {},
3824
- ...config.endpoint ? { endpoint: config.endpoint } : {}
3825
- });
3826
- }
3827
- function createStorageDriver() {
3828
- const driver = process.env.STORAGE_DRIVER ?? "local";
3829
- if (driver === "s3") {
3830
- return new S3StorageDriver(createS3Client());
3831
- }
3832
- return new LocalStorageDriver;
3833
- }
3834
-
3835
971
  // ../../src/bootstrap/providers/storage.ts
972
+ import { createStorageDriver, StorageManager } from "@getstrata/core/storage/storage";
3836
973
  var storageProvider = {
3837
974
  name: "core.storage",
3838
975
  register({ dependencies }) {
@@ -3841,6 +978,10 @@ var storageProvider = {
3841
978
  };
3842
979
  var storage_default = storageProvider;
3843
980
 
981
+ // ../../src/bootstrap/providers/view.ts
982
+ import { currentRequestMeta } from "@getstrata/core/http/requestMetaContext";
983
+ import { DEFAULT_VIEWS_DIRECTORY, EtaViewEngine, resolveWebLayoutData } from "@getstrata/core/view";
984
+
3844
985
  // ../../src/config/frontend.ts
3845
986
  function readFrontendMode() {
3846
987
  const mode = (process.env.FRONTEND_MODE ?? "api").trim();
@@ -3855,215 +996,10 @@ function readFrontendMode() {
3855
996
  function isViewsEnabled() {
3856
997
  return readFrontendMode() === "server-htmx";
3857
998
  }
3858
-
3859
- // ../../src/core/http/requestMetaContext.ts
3860
- var requestMetaContext = createAsyncContextStore("@getstrata/requestMetaContext");
3861
- function currentRequestMeta() {
3862
- return requestMetaContext.getStore() ?? {
3863
- ipAddress: null,
3864
- userAgent: null
3865
- };
3866
- }
3867
-
3868
- // ../../src/core/view/etaViewEngine.ts
3869
- import { join as join4 } from "path";
3870
- import { Eta } from "eta";
3871
- var DEFAULT_VIEWS_DIRECTORY = join4(process.cwd(), "resources/views");
3872
- var DEFAULT_LAYOUT = "layouts/app.eta";
3873
-
3874
- class EtaViewEngine {
3875
- eta;
3876
- resolveLayoutData;
3877
- constructor(viewsDirectory = DEFAULT_VIEWS_DIRECTORY, resolveLayoutData) {
3878
- this.eta = new Eta({
3879
- views: viewsDirectory,
3880
- autoTrim: false
3881
- });
3882
- this.resolveLayoutData = resolveLayoutData;
3883
- }
3884
- async render(name, data = {}, options = {}) {
3885
- const template = name.endsWith(".eta") ? name : `${name}.eta`;
3886
- const layoutData = this.resolveLayoutData ? await this.resolveLayoutData() : {};
3887
- const mergedData = { ...layoutData, ...data };
3888
- const body = await this.eta.renderAsync(template, mergedData);
3889
- const layout = options.layout ?? DEFAULT_LAYOUT;
3890
- if (layout === false) {
3891
- return body;
3892
- }
3893
- const layoutTemplate = layout.endsWith(".eta") ? layout : `${layout}.eta`;
3894
- return await this.eta.renderAsync(layoutTemplate, {
3895
- ...mergedData,
3896
- body
3897
- });
3898
- }
3899
- }
3900
- // ../../src/core/http/cookies.ts
3901
- function readRequestCookie(request, name) {
3902
- const cookies = request.cookies;
3903
- if (cookies && typeof cookies.get === "function") {
3904
- const value = cookies.get(name);
3905
- if (value) {
3906
- return value;
3907
- }
3908
- }
3909
- const header = request.headers.get("cookie");
3910
- if (!header) {
3911
- return null;
3912
- }
3913
- for (const part of header.split(";")) {
3914
- const idx = part.indexOf("=");
3915
- if (idx === -1)
3916
- continue;
3917
- const cookieName = part.slice(0, idx).trim();
3918
- if (cookieName !== name)
3919
- continue;
3920
- return decodeURIComponent(part.slice(idx + 1).trim());
3921
- }
3922
- return null;
3923
- }
3924
-
3925
- // ../../src/core/http/csrfToken.ts
3926
- var CSRF_COOKIE = "workhub_csrf";
3927
- var CSRF_TTL_MS = 60 * 60 * 1000;
3928
- function resolveCsrfSecret() {
3929
- return process.env.SESSION_SECRET?.trim() || process.env.OAUTH_STATE_SECRET?.trim() || process.env.ADMIN_API_TOKEN?.trim() || "workhub-dev-csrf-secret";
3930
- }
3931
- function csrfVerifyOptions() {
3932
- return { secret: resolveCsrfSecret(), maxAge: CSRF_TTL_MS };
3933
- }
3934
- function createCsrfTokenCookie() {
3935
- const token = Bun.CSRF.generate(resolveCsrfSecret(), { expiresIn: CSRF_TTL_MS });
3936
- return {
3937
- token,
3938
- cookie: `${CSRF_COOKIE}=${encodeURIComponent(token)}; Path=/; SameSite=Lax; Max-Age=${Math.floor(CSRF_TTL_MS / 1000)}`
3939
- };
3940
- }
3941
- function resolveCsrfToken(request) {
3942
- const cookieValue = readRequestCookie(request, CSRF_COOKIE);
3943
- if (cookieValue && Bun.CSRF.verify(cookieValue, csrfVerifyOptions())) {
3944
- return { token: cookieValue };
3945
- }
3946
- return createCsrfTokenCookie();
3947
- }
3948
- function resolveCsrfTokenForRequest(request) {
3949
- const metaToken = currentRequestMeta().csrfToken;
3950
- if (metaToken) {
3951
- return metaToken;
3952
- }
3953
- return resolveCsrfToken(request).token;
3954
- }
3955
-
3956
- // ../../src/core/http/flashSession.ts
3957
- import { createHmac as createHmac3, timingSafeEqual as timingSafeEqual2 } from "crypto";
3958
- var FLASH_COOKIE = "workhub_flash";
3959
- var FLASH_TTL_MS = 60 * 1000;
3960
- function resolveFlashSecret() {
3961
- return process.env.SESSION_SECRET?.trim() || process.env.OAUTH_STATE_SECRET?.trim() || "workhub-dev-flash-secret";
3962
- }
3963
- function signFlashPayload(payload, issuedAt) {
3964
- const signature = createHmac3("sha256", resolveFlashSecret()).update(`${payload}.${issuedAt}`).digest("hex");
3965
- return `${payload}.${issuedAt}.${signature}`;
3966
- }
3967
- function readFlashCookie(request) {
3968
- const cookieHeader = request.headers.get("cookie");
3969
- if (!cookieHeader) {
3970
- return null;
3971
- }
3972
- for (const part of cookieHeader.split(";")) {
3973
- const [name, ...rest] = part.trim().split("=");
3974
- if (name === FLASH_COOKIE) {
3975
- return decodeURIComponent(rest.join("="));
3976
- }
3977
- }
3978
- return null;
3979
- }
3980
- function parseFlashCookie(cookieValue) {
3981
- const parts = cookieValue.split(".");
3982
- if (parts.length < 3) {
3983
- return null;
3984
- }
3985
- const signature = parts.pop();
3986
- const issuedAtRaw = parts.pop();
3987
- const payload = parts.join(".");
3988
- if (!signature || !issuedAtRaw || !payload) {
3989
- return null;
3990
- }
3991
- const issuedAt = Number.parseInt(issuedAtRaw, 10);
3992
- if (!Number.isFinite(issuedAt) || Date.now() - issuedAt > FLASH_TTL_MS) {
3993
- return null;
3994
- }
3995
- const expectedSignature = signFlashPayload(payload, issuedAt).split(".").pop();
3996
- if (!expectedSignature) {
3997
- return null;
3998
- }
3999
- const expectedBuffer = Buffer.from(expectedSignature);
4000
- const actualBuffer = Buffer.from(signature);
4001
- if (expectedBuffer.length !== actualBuffer.length) {
4002
- return null;
4003
- }
4004
- if (!timingSafeEqual2(expectedBuffer, actualBuffer)) {
4005
- return null;
4006
- }
4007
- try {
4008
- const parsed = JSON.parse(Buffer.from(payload, "base64url").toString("utf8"));
4009
- if (!parsed?.message || typeof parsed.message !== "string") {
4010
- return null;
4011
- }
4012
- if (parsed.level !== "success" && parsed.level !== "error" && parsed.level !== "info") {
4013
- return null;
4014
- }
4015
- return parsed;
4016
- } catch {
4017
- return null;
4018
- }
4019
- }
4020
- function pullFlash(request) {
4021
- const cookieValue = readFlashCookie(request);
4022
- if (!cookieValue) {
4023
- return null;
4024
- }
4025
- return parseFlashCookie(cookieValue);
999
+ function isSpaEnabled() {
1000
+ return readFrontendMode() === "spa-react";
4026
1001
  }
4027
1002
 
4028
- // ../../src/core/view/webLayoutData.ts
4029
- async function resolveWebLayoutData(container, request) {
4030
- const csrfToken = request ? resolveCsrfTokenForRequest(request) : "";
4031
- const flash = request ? currentRequestMeta().flash ?? pullFlash(request) : null;
4032
- const authUser = currentAuthUser();
4033
- if (!authUser) {
4034
- return { authUser: null, csrfToken, flash };
4035
- }
4036
- const userId = Number(authUser.id);
4037
- if (!Number.isInteger(userId) || userId <= 0) {
4038
- return { authUser: null, csrfToken, flash };
4039
- }
4040
- if (!container.has(tokenServiceToken)) {
4041
- return {
4042
- authUser: {
4043
- id: userId,
4044
- email: "",
4045
- role: authUser.role ?? "member"
4046
- },
4047
- csrfToken,
4048
- flash
4049
- };
4050
- }
4051
- const tokenService = container.resolve(tokenServiceToken);
4052
- try {
4053
- const user = await tokenService.findByIdOrThrow(userId);
4054
- return {
4055
- authUser: {
4056
- id: userId,
4057
- email: user.email ?? "",
4058
- role: authUser.role ?? user.role ?? "member"
4059
- },
4060
- csrfToken,
4061
- flash
4062
- };
4063
- } catch {
4064
- return { authUser: null, csrfToken, flash };
4065
- }
4066
- }
4067
1003
  // ../../src/bootstrap/providers/view.ts
4068
1004
  var CORE_VIEW_TOKEN = "core.view";
4069
1005
  var VIEW_DIRECTORY_CONFIG_KEY = "view.directory";
@@ -4099,6 +1035,13 @@ var TEST_MEMBER_API_TOKEN = "workhub-member-test-token";
4099
1035
  // ../../src/domain/scim.ts
4100
1036
  var TEST_SCIM_BEARER_TOKEN = "workhub-scim-test-token";
4101
1037
  var DEFAULT_SCIM_BEARER_TOKEN = TEST_SCIM_BEARER_TOKEN;
1038
+ var SCIM_SCHEMAS = {
1039
+ user: "urn:ietf:params:scim:schemas:core:2.0:User",
1040
+ group: "urn:ietf:params:scim:schemas:core:2.0:Group",
1041
+ listResponse: "urn:ietf:params:scim:api:messages:2.0:ListResponse",
1042
+ patchOp: "urn:ietf:params:scim:api:messages:2.0:PatchOp",
1043
+ serviceProviderConfig: "urn:ietf:params:scim:schemas:core:2.0:ServiceProviderConfig"
1044
+ };
4102
1045
 
4103
1046
  // ../../src/bootstrap/secretsGuard.ts
4104
1047
  var DEFAULT_TOKENS = new Set([TEST_ADMIN_API_TOKEN, TEST_MEMBER_API_TOKEN]);