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