@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.
- package/dist/bootstrap/http/securedRouteModelBinding.d.ts +2 -2
- package/dist/bootstrap/schedule.d.ts +2 -1
- package/dist/bootstrap/web/forms.d.ts +1 -1
- package/dist/entries/applicationRegistry.js +2 -0
- package/dist/entries/buildModuleRoutes.js +2 -0
- package/dist/entries/buildWebModuleRoutes.js +2 -0
- package/dist/entries/cache/modelCacheTags.js +2 -0
- package/dist/entries/config.js +2 -0
- package/dist/entries/context.js +76 -3157
- package/dist/entries/contracts.js +2 -0
- package/dist/entries/createRoutes.js +1468 -0
- package/dist/entries/createSpaRoutes.js +2 -0
- package/dist/entries/createWebRoutes.js +2 -0
- package/dist/entries/dependencies.js +76 -3157
- package/dist/entries/discoverModules.js +2 -0
- package/dist/entries/health.js +3 -0
- package/dist/entries/http/securedRouteModelBinding.js +6 -293
- package/dist/entries/httpKernel.js +2 -0
- package/dist/entries/listeners/invalidateCacheOnModelWrite.js +2 -0
- package/dist/entries/membershipService.js +2 -0
- package/dist/entries/metricsRoutes.js +2 -0
- package/dist/entries/providers/view.js +6 -623
- package/dist/entries/providers.js +69 -3157
- package/dist/entries/queue/defaultJobs.js +7 -465
- package/dist/entries/routeRegistry.js +2 -0
- package/dist/entries/schedule.js +49 -0
- package/dist/entries/secretsGuard.js +9 -0
- package/dist/entries/web/forms.js +4 -18
- package/dist/entries/web/routing.js +18 -304
- package/dist/entries/web/server.js +2 -0
- package/dist/entries/web/session.js +3 -26
- package/dist/entries/web/slug.js +2 -0
- package/dist/index-sfreg6q3.js +0 -0
- package/dist/index.js +69 -3322
- package/package.json +12 -2
package/dist/index.js
CHANGED
|
@@ -552,6 +552,14 @@ import {
|
|
|
552
552
|
resolveService
|
|
553
553
|
} from "@getstrata/core/contracts/di";
|
|
554
554
|
|
|
555
|
+
// ../../src/bootstrap/providers/auth.ts
|
|
556
|
+
import {
|
|
557
|
+
AuthManager,
|
|
558
|
+
CompositeGuard,
|
|
559
|
+
DatabaseTokenGuard,
|
|
560
|
+
GuestGuard
|
|
561
|
+
} from "@getstrata/core/auth/guard";
|
|
562
|
+
|
|
555
563
|
// ../../src/config/auth.ts
|
|
556
564
|
var authConfig = {
|
|
557
565
|
allowDevHeaders: (process.env.AUTH_DEV_HEADERS ?? "true") !== "false",
|
|
@@ -901,143 +909,6 @@ import { resolveDefaultTokenExpiryDays as resolveDefaultTokenExpiryDays2 } from
|
|
|
901
909
|
// ../../src/modules/user/provider.ts
|
|
902
910
|
var tokenServiceToken = CORE_TOKEN_SERVICE_TOKEN;
|
|
903
911
|
|
|
904
|
-
// ../../src/core/errors/http.ts
|
|
905
|
-
class HttpError extends Error {
|
|
906
|
-
status;
|
|
907
|
-
details;
|
|
908
|
-
constructor(status, message, details) {
|
|
909
|
-
super(message);
|
|
910
|
-
this.name = new.target.name;
|
|
911
|
-
this.status = status;
|
|
912
|
-
this.details = details;
|
|
913
|
-
}
|
|
914
|
-
}
|
|
915
|
-
|
|
916
|
-
class BadRequestError extends HttpError {
|
|
917
|
-
constructor(message = "Bad Request", details) {
|
|
918
|
-
super(400, message, details);
|
|
919
|
-
}
|
|
920
|
-
}
|
|
921
|
-
class ConflictError extends HttpError {
|
|
922
|
-
constructor(message = "Conflict", details) {
|
|
923
|
-
super(409, message, details);
|
|
924
|
-
}
|
|
925
|
-
}
|
|
926
|
-
|
|
927
|
-
class UnprocessableEntityError extends HttpError {
|
|
928
|
-
constructor(message = "Unprocessable Entity", details) {
|
|
929
|
-
super(422, message, details);
|
|
930
|
-
}
|
|
931
|
-
}
|
|
932
|
-
class ForbiddenError2 extends HttpError {
|
|
933
|
-
constructor(message = "Forbidden", details) {
|
|
934
|
-
super(403, message, details);
|
|
935
|
-
}
|
|
936
|
-
}
|
|
937
|
-
|
|
938
|
-
class UnauthorizedError2 extends HttpError {
|
|
939
|
-
constructor(message = "Unauthorized", details) {
|
|
940
|
-
super(401, message, details);
|
|
941
|
-
}
|
|
942
|
-
}
|
|
943
|
-
class PreconditionFailedError extends HttpError {
|
|
944
|
-
constructor(message = "Precondition Failed", details) {
|
|
945
|
-
super(412, message, details);
|
|
946
|
-
}
|
|
947
|
-
}
|
|
948
|
-
|
|
949
|
-
// ../../src/core/auth/authContext.ts
|
|
950
|
-
var authContext = createAsyncContextStore("@getstrata/authContext");
|
|
951
|
-
function currentAuthUser() {
|
|
952
|
-
return authContext.getStore() ?? null;
|
|
953
|
-
}
|
|
954
|
-
|
|
955
|
-
// ../../src/core/auth/guard.ts
|
|
956
|
-
function devHeaderAbilities(role) {
|
|
957
|
-
if (role === "admin") {
|
|
958
|
-
return [...ADMIN_ABILITIES];
|
|
959
|
-
}
|
|
960
|
-
return [...MEMBER_ABILITIES];
|
|
961
|
-
}
|
|
962
|
-
|
|
963
|
-
class GuestGuard {
|
|
964
|
-
resolve(request) {
|
|
965
|
-
const userId = request.headers.get("x-authenticated-user-id");
|
|
966
|
-
if (!userId) {
|
|
967
|
-
return null;
|
|
968
|
-
}
|
|
969
|
-
const role = request.headers.get("x-authenticated-user-role");
|
|
970
|
-
return {
|
|
971
|
-
id: userId,
|
|
972
|
-
abilities: devHeaderAbilities(role),
|
|
973
|
-
...role ? { role } : {}
|
|
974
|
-
};
|
|
975
|
-
}
|
|
976
|
-
}
|
|
977
|
-
class DatabaseTokenGuard {
|
|
978
|
-
container;
|
|
979
|
-
constructor(container) {
|
|
980
|
-
this.container = container;
|
|
981
|
-
}
|
|
982
|
-
async resolve(request) {
|
|
983
|
-
const authorization = request.headers.get("authorization");
|
|
984
|
-
if (!authorization?.startsWith("Bearer ")) {
|
|
985
|
-
return null;
|
|
986
|
-
}
|
|
987
|
-
const token = authorization.slice("Bearer ".length).trim();
|
|
988
|
-
if (!token) {
|
|
989
|
-
return null;
|
|
990
|
-
}
|
|
991
|
-
if (!this.container.has(tokenServiceToken)) {
|
|
992
|
-
return null;
|
|
993
|
-
}
|
|
994
|
-
const tokenService = this.container.resolve(tokenServiceToken);
|
|
995
|
-
return await tokenService.resolveUserFromToken(token);
|
|
996
|
-
}
|
|
997
|
-
}
|
|
998
|
-
|
|
999
|
-
class CompositeGuard {
|
|
1000
|
-
guards;
|
|
1001
|
-
constructor(guards) {
|
|
1002
|
-
this.guards = guards;
|
|
1003
|
-
}
|
|
1004
|
-
async resolve(request) {
|
|
1005
|
-
for (const guard of this.guards) {
|
|
1006
|
-
const user = await Promise.resolve(guard.resolve(request));
|
|
1007
|
-
if (user) {
|
|
1008
|
-
return user;
|
|
1009
|
-
}
|
|
1010
|
-
}
|
|
1011
|
-
return null;
|
|
1012
|
-
}
|
|
1013
|
-
}
|
|
1014
|
-
|
|
1015
|
-
class AuthManager {
|
|
1016
|
-
guard;
|
|
1017
|
-
constructor(guard) {
|
|
1018
|
-
this.guard = guard;
|
|
1019
|
-
}
|
|
1020
|
-
async resolve(request) {
|
|
1021
|
-
if (request) {
|
|
1022
|
-
return await Promise.resolve(this.guard.resolve(request));
|
|
1023
|
-
}
|
|
1024
|
-
return currentAuthUser();
|
|
1025
|
-
}
|
|
1026
|
-
user(request) {
|
|
1027
|
-
return this.resolve(request);
|
|
1028
|
-
}
|
|
1029
|
-
async check(request) {
|
|
1030
|
-
return await this.user(request) !== null;
|
|
1031
|
-
}
|
|
1032
|
-
async requireUser(request) {
|
|
1033
|
-
const user = await this.user(request);
|
|
1034
|
-
if (!user) {
|
|
1035
|
-
throw new UnauthorizedError2;
|
|
1036
|
-
}
|
|
1037
|
-
return user;
|
|
1038
|
-
}
|
|
1039
|
-
}
|
|
1040
|
-
|
|
1041
912
|
// ../../src/core/auth/sessionCookie.ts
|
|
1042
913
|
import { createHmac, timingSafeEqual } from "crypto";
|
|
1043
914
|
var SESSION_COOKIE = "workhub_session";
|
|
@@ -1138,378 +1009,8 @@ var authProvider = {
|
|
|
1138
1009
|
};
|
|
1139
1010
|
var auth_default = authProvider;
|
|
1140
1011
|
|
|
1141
|
-
// ../../src/
|
|
1142
|
-
|
|
1143
|
-
var KEY_PREFIX = "workhub:cache:";
|
|
1144
|
-
var TAG_PREFIX = "workhub:cache:tag:";
|
|
1145
|
-
|
|
1146
|
-
class RedisCacheStore {
|
|
1147
|
-
ttlMs;
|
|
1148
|
-
maxEntries;
|
|
1149
|
-
client;
|
|
1150
|
-
inflight = new Map;
|
|
1151
|
-
keyTags = new Map;
|
|
1152
|
-
constructor(redisUrl, ttlMs, maxEntries) {
|
|
1153
|
-
this.ttlMs = ttlMs;
|
|
1154
|
-
this.maxEntries = maxEntries;
|
|
1155
|
-
this.client = new RedisClient(redisUrl);
|
|
1156
|
-
}
|
|
1157
|
-
async get(key) {
|
|
1158
|
-
const raw = await this.client.get(this.storageKey(key));
|
|
1159
|
-
if (raw === null) {
|
|
1160
|
-
return;
|
|
1161
|
-
}
|
|
1162
|
-
return JSON.parse(raw);
|
|
1163
|
-
}
|
|
1164
|
-
async set(key, value, ttlMs) {
|
|
1165
|
-
const resolvedTtlMs = ttlMs ?? this.ttlMs;
|
|
1166
|
-
const payload = JSON.stringify(value);
|
|
1167
|
-
if (resolvedTtlMs > 0) {
|
|
1168
|
-
await this.client.psetex(this.storageKey(key), resolvedTtlMs, payload);
|
|
1169
|
-
} else {
|
|
1170
|
-
await this.client.set(this.storageKey(key), payload);
|
|
1171
|
-
}
|
|
1172
|
-
await this.enforceMaxEntries();
|
|
1173
|
-
}
|
|
1174
|
-
async getOrSet(key, loader, ttlMs) {
|
|
1175
|
-
const cached = await this.get(key);
|
|
1176
|
-
if (cached !== undefined) {
|
|
1177
|
-
return cached;
|
|
1178
|
-
}
|
|
1179
|
-
const inflightRequest = this.inflight.get(key);
|
|
1180
|
-
if (inflightRequest) {
|
|
1181
|
-
return inflightRequest;
|
|
1182
|
-
}
|
|
1183
|
-
const pendingRequest = loader().then(async (value) => {
|
|
1184
|
-
await this.set(key, value, ttlMs);
|
|
1185
|
-
return value;
|
|
1186
|
-
}).finally(() => {
|
|
1187
|
-
this.inflight.delete(key);
|
|
1188
|
-
});
|
|
1189
|
-
this.inflight.set(key, pendingRequest);
|
|
1190
|
-
return pendingRequest;
|
|
1191
|
-
}
|
|
1192
|
-
async attachTags(key, tags) {
|
|
1193
|
-
if (tags.length === 0) {
|
|
1194
|
-
return;
|
|
1195
|
-
}
|
|
1196
|
-
let tagsForKey = this.keyTags.get(key);
|
|
1197
|
-
if (!tagsForKey) {
|
|
1198
|
-
tagsForKey = new Set;
|
|
1199
|
-
this.keyTags.set(key, tagsForKey);
|
|
1200
|
-
}
|
|
1201
|
-
for (const tag of tags) {
|
|
1202
|
-
tagsForKey.add(tag);
|
|
1203
|
-
await this.client.sadd(this.tagKey(tag), key);
|
|
1204
|
-
}
|
|
1205
|
-
}
|
|
1206
|
-
async flushTags(tags) {
|
|
1207
|
-
const keysToRemove = new Set;
|
|
1208
|
-
for (const tag of tags) {
|
|
1209
|
-
const members = await this.client.smembers(this.tagKey(tag));
|
|
1210
|
-
for (const member of members) {
|
|
1211
|
-
keysToRemove.add(member);
|
|
1212
|
-
}
|
|
1213
|
-
}
|
|
1214
|
-
let removed = 0;
|
|
1215
|
-
for (const key of keysToRemove) {
|
|
1216
|
-
if (await this.invalidate(key)) {
|
|
1217
|
-
removed += 1;
|
|
1218
|
-
}
|
|
1219
|
-
}
|
|
1220
|
-
for (const tag of tags) {
|
|
1221
|
-
await this.client.del(this.tagKey(tag));
|
|
1222
|
-
}
|
|
1223
|
-
return removed;
|
|
1224
|
-
}
|
|
1225
|
-
async invalidate(key) {
|
|
1226
|
-
const deleted = await this.client.del(this.storageKey(key));
|
|
1227
|
-
await this.detachKeyFromTags(key);
|
|
1228
|
-
return deleted > 0;
|
|
1229
|
-
}
|
|
1230
|
-
async invalidateByPrefix(prefix) {
|
|
1231
|
-
const keys = await this.client.keys(`${KEY_PREFIX}*`);
|
|
1232
|
-
let removed = 0;
|
|
1233
|
-
for (const storageKey of keys) {
|
|
1234
|
-
const key = storageKey.slice(KEY_PREFIX.length);
|
|
1235
|
-
if (key === prefix || key.startsWith(`${prefix}?`)) {
|
|
1236
|
-
if (await this.invalidate(key)) {
|
|
1237
|
-
removed += 1;
|
|
1238
|
-
}
|
|
1239
|
-
}
|
|
1240
|
-
}
|
|
1241
|
-
return removed;
|
|
1242
|
-
}
|
|
1243
|
-
async clear() {
|
|
1244
|
-
const keys = await this.client.keys(`${KEY_PREFIX}*`);
|
|
1245
|
-
if (keys.length > 0) {
|
|
1246
|
-
await this.client.del(...keys);
|
|
1247
|
-
}
|
|
1248
|
-
const tagKeys = await this.client.keys(`${TAG_PREFIX}*`);
|
|
1249
|
-
if (tagKeys.length > 0) {
|
|
1250
|
-
await this.client.del(...tagKeys);
|
|
1251
|
-
}
|
|
1252
|
-
this.inflight.clear();
|
|
1253
|
-
this.keyTags.clear();
|
|
1254
|
-
}
|
|
1255
|
-
async size() {
|
|
1256
|
-
const keys = await this.client.keys(`${KEY_PREFIX}*`);
|
|
1257
|
-
return keys.length;
|
|
1258
|
-
}
|
|
1259
|
-
storageKey(key) {
|
|
1260
|
-
return `${KEY_PREFIX}${key}`;
|
|
1261
|
-
}
|
|
1262
|
-
tagKey(tag) {
|
|
1263
|
-
return `${TAG_PREFIX}${tag}`;
|
|
1264
|
-
}
|
|
1265
|
-
async detachKeyFromTags(key) {
|
|
1266
|
-
const tags = this.keyTags.get(key);
|
|
1267
|
-
if (!tags) {
|
|
1268
|
-
return;
|
|
1269
|
-
}
|
|
1270
|
-
for (const tag of tags) {
|
|
1271
|
-
await this.client.srem(this.tagKey(tag), key);
|
|
1272
|
-
}
|
|
1273
|
-
this.keyTags.delete(key);
|
|
1274
|
-
}
|
|
1275
|
-
async enforceMaxEntries() {
|
|
1276
|
-
const keys = await this.client.keys(`${KEY_PREFIX}*`);
|
|
1277
|
-
if (keys.length <= this.maxEntries) {
|
|
1278
|
-
return;
|
|
1279
|
-
}
|
|
1280
|
-
const overflow = keys.length - this.maxEntries;
|
|
1281
|
-
const keysToRemove = keys.slice(0, overflow);
|
|
1282
|
-
if (keysToRemove.length > 0) {
|
|
1283
|
-
await this.client.del(...keysToRemove);
|
|
1284
|
-
}
|
|
1285
|
-
}
|
|
1286
|
-
}
|
|
1287
|
-
var redisCacheStore_default = RedisCacheStore;
|
|
1288
|
-
|
|
1289
|
-
// ../../src/core/cache/simpleCache.ts
|
|
1290
|
-
class SimpleCache {
|
|
1291
|
-
ttlMs;
|
|
1292
|
-
maxEntries;
|
|
1293
|
-
cache = new Map;
|
|
1294
|
-
inflight = new Map;
|
|
1295
|
-
tagIndex = new Map;
|
|
1296
|
-
keyTags = new Map;
|
|
1297
|
-
constructor(ttlMs = 3600000, maxEntries = 100) {
|
|
1298
|
-
this.ttlMs = ttlMs;
|
|
1299
|
-
this.maxEntries = maxEntries;
|
|
1300
|
-
if (!Number.isFinite(ttlMs) || ttlMs < 0) {
|
|
1301
|
-
throw new RangeError("ttlMs must be a non-negative number.");
|
|
1302
|
-
}
|
|
1303
|
-
if (!Number.isInteger(maxEntries) || maxEntries < 1) {
|
|
1304
|
-
throw new RangeError("maxEntries must be a positive integer.");
|
|
1305
|
-
}
|
|
1306
|
-
}
|
|
1307
|
-
get(key) {
|
|
1308
|
-
return this.getFreshEntry(key)?.value;
|
|
1309
|
-
}
|
|
1310
|
-
set(key, value, ttlMs) {
|
|
1311
|
-
const now = Date.now();
|
|
1312
|
-
const resolvedTtlMs = ttlMs ?? this.ttlMs;
|
|
1313
|
-
this.cache.set(key, {
|
|
1314
|
-
value,
|
|
1315
|
-
expiresAt: now + resolvedTtlMs,
|
|
1316
|
-
lastAccessedAt: now
|
|
1317
|
-
});
|
|
1318
|
-
this.evictOverflow();
|
|
1319
|
-
}
|
|
1320
|
-
async getOrSet(key, loader, ttlMs) {
|
|
1321
|
-
this.pruneExpired();
|
|
1322
|
-
const cachedEntry = this.getFreshEntry(key);
|
|
1323
|
-
if (cachedEntry) {
|
|
1324
|
-
return cachedEntry.value;
|
|
1325
|
-
}
|
|
1326
|
-
const inflightRequest = this.inflight.get(key);
|
|
1327
|
-
if (inflightRequest) {
|
|
1328
|
-
return inflightRequest;
|
|
1329
|
-
}
|
|
1330
|
-
const pendingRequest = loader().then((value) => {
|
|
1331
|
-
this.set(key, value, ttlMs);
|
|
1332
|
-
return value;
|
|
1333
|
-
}).finally(() => {
|
|
1334
|
-
this.inflight.delete(key);
|
|
1335
|
-
});
|
|
1336
|
-
this.inflight.set(key, pendingRequest);
|
|
1337
|
-
return pendingRequest;
|
|
1338
|
-
}
|
|
1339
|
-
attachTags(key, tags) {
|
|
1340
|
-
if (tags.length === 0) {
|
|
1341
|
-
return;
|
|
1342
|
-
}
|
|
1343
|
-
let tagsForKey = this.keyTags.get(key);
|
|
1344
|
-
if (!tagsForKey) {
|
|
1345
|
-
tagsForKey = new Set;
|
|
1346
|
-
this.keyTags.set(key, tagsForKey);
|
|
1347
|
-
}
|
|
1348
|
-
for (const tag of tags) {
|
|
1349
|
-
tagsForKey.add(tag);
|
|
1350
|
-
let keysForTag = this.tagIndex.get(tag);
|
|
1351
|
-
if (!keysForTag) {
|
|
1352
|
-
keysForTag = new Set;
|
|
1353
|
-
this.tagIndex.set(tag, keysForTag);
|
|
1354
|
-
}
|
|
1355
|
-
keysForTag.add(key);
|
|
1356
|
-
}
|
|
1357
|
-
}
|
|
1358
|
-
flushTags(tags) {
|
|
1359
|
-
const keysToRemove = new Set;
|
|
1360
|
-
for (const tag of tags) {
|
|
1361
|
-
const keys = this.tagIndex.get(tag);
|
|
1362
|
-
if (!keys) {
|
|
1363
|
-
continue;
|
|
1364
|
-
}
|
|
1365
|
-
for (const key of keys) {
|
|
1366
|
-
keysToRemove.add(key);
|
|
1367
|
-
}
|
|
1368
|
-
}
|
|
1369
|
-
let removed = 0;
|
|
1370
|
-
for (const key of keysToRemove) {
|
|
1371
|
-
if (this.invalidate(key)) {
|
|
1372
|
-
removed += 1;
|
|
1373
|
-
}
|
|
1374
|
-
}
|
|
1375
|
-
for (const tag of tags) {
|
|
1376
|
-
this.tagIndex.delete(tag);
|
|
1377
|
-
}
|
|
1378
|
-
return removed;
|
|
1379
|
-
}
|
|
1380
|
-
invalidate(key) {
|
|
1381
|
-
const removed = this.cache.delete(key);
|
|
1382
|
-
if (removed) {
|
|
1383
|
-
this.detachKeyFromTags(key);
|
|
1384
|
-
}
|
|
1385
|
-
return removed;
|
|
1386
|
-
}
|
|
1387
|
-
invalidateByPrefix(prefix) {
|
|
1388
|
-
let removed = 0;
|
|
1389
|
-
for (const key of [...this.cache.keys()]) {
|
|
1390
|
-
if (key === prefix || key.startsWith(`${prefix}?`)) {
|
|
1391
|
-
if (this.invalidate(key)) {
|
|
1392
|
-
removed += 1;
|
|
1393
|
-
}
|
|
1394
|
-
}
|
|
1395
|
-
}
|
|
1396
|
-
return removed;
|
|
1397
|
-
}
|
|
1398
|
-
clear() {
|
|
1399
|
-
this.cache.clear();
|
|
1400
|
-
this.inflight.clear();
|
|
1401
|
-
this.tagIndex.clear();
|
|
1402
|
-
this.keyTags.clear();
|
|
1403
|
-
}
|
|
1404
|
-
size() {
|
|
1405
|
-
this.pruneExpired();
|
|
1406
|
-
return this.cache.size;
|
|
1407
|
-
}
|
|
1408
|
-
detachKeyFromTags(key) {
|
|
1409
|
-
const tags = this.keyTags.get(key);
|
|
1410
|
-
if (!tags) {
|
|
1411
|
-
return;
|
|
1412
|
-
}
|
|
1413
|
-
for (const tag of tags) {
|
|
1414
|
-
const keys = this.tagIndex.get(tag);
|
|
1415
|
-
if (!keys) {
|
|
1416
|
-
continue;
|
|
1417
|
-
}
|
|
1418
|
-
keys.delete(key);
|
|
1419
|
-
if (keys.size === 0) {
|
|
1420
|
-
this.tagIndex.delete(tag);
|
|
1421
|
-
}
|
|
1422
|
-
}
|
|
1423
|
-
this.keyTags.delete(key);
|
|
1424
|
-
}
|
|
1425
|
-
getFreshEntry(key) {
|
|
1426
|
-
const entry = this.cache.get(key);
|
|
1427
|
-
if (!entry) {
|
|
1428
|
-
return;
|
|
1429
|
-
}
|
|
1430
|
-
if (entry.expiresAt <= Date.now()) {
|
|
1431
|
-
this.invalidate(key);
|
|
1432
|
-
return;
|
|
1433
|
-
}
|
|
1434
|
-
entry.lastAccessedAt = Date.now();
|
|
1435
|
-
return entry;
|
|
1436
|
-
}
|
|
1437
|
-
pruneExpired() {
|
|
1438
|
-
const now = Date.now();
|
|
1439
|
-
for (const [key, entry] of this.cache.entries()) {
|
|
1440
|
-
if (entry.expiresAt <= now) {
|
|
1441
|
-
this.invalidate(key);
|
|
1442
|
-
}
|
|
1443
|
-
}
|
|
1444
|
-
}
|
|
1445
|
-
evictOverflow() {
|
|
1446
|
-
while (this.cache.size > this.maxEntries) {
|
|
1447
|
-
let oldestKey;
|
|
1448
|
-
let oldestAccessTime = Number.POSITIVE_INFINITY;
|
|
1449
|
-
for (const [key, entry] of this.cache.entries()) {
|
|
1450
|
-
if (entry.lastAccessedAt < oldestAccessTime) {
|
|
1451
|
-
oldestAccessTime = entry.lastAccessedAt;
|
|
1452
|
-
oldestKey = key;
|
|
1453
|
-
}
|
|
1454
|
-
}
|
|
1455
|
-
if (!oldestKey) {
|
|
1456
|
-
return;
|
|
1457
|
-
}
|
|
1458
|
-
this.invalidate(oldestKey);
|
|
1459
|
-
}
|
|
1460
|
-
}
|
|
1461
|
-
}
|
|
1462
|
-
var simpleCache_default = SimpleCache;
|
|
1463
|
-
|
|
1464
|
-
// ../../src/core/cache/simpleCacheStore.ts
|
|
1465
|
-
class SimpleCacheStore {
|
|
1466
|
-
cache;
|
|
1467
|
-
constructor(cache) {
|
|
1468
|
-
this.cache = cache;
|
|
1469
|
-
}
|
|
1470
|
-
get(key) {
|
|
1471
|
-
return Promise.resolve(this.cache.get(key));
|
|
1472
|
-
}
|
|
1473
|
-
set(key, value, ttlMs) {
|
|
1474
|
-
this.cache.set(key, value, ttlMs);
|
|
1475
|
-
return Promise.resolve();
|
|
1476
|
-
}
|
|
1477
|
-
getOrSet(key, loader, ttlMs) {
|
|
1478
|
-
return this.cache.getOrSet(key, loader, ttlMs);
|
|
1479
|
-
}
|
|
1480
|
-
attachTags(key, tags) {
|
|
1481
|
-
this.cache.attachTags(key, tags);
|
|
1482
|
-
return Promise.resolve();
|
|
1483
|
-
}
|
|
1484
|
-
flushTags(tags) {
|
|
1485
|
-
return Promise.resolve(this.cache.flushTags(tags));
|
|
1486
|
-
}
|
|
1487
|
-
invalidate(key) {
|
|
1488
|
-
return Promise.resolve(this.cache.invalidate(key));
|
|
1489
|
-
}
|
|
1490
|
-
invalidateByPrefix(prefix) {
|
|
1491
|
-
return Promise.resolve(this.cache.invalidateByPrefix(prefix));
|
|
1492
|
-
}
|
|
1493
|
-
clear() {
|
|
1494
|
-
this.cache.clear();
|
|
1495
|
-
return Promise.resolve();
|
|
1496
|
-
}
|
|
1497
|
-
size() {
|
|
1498
|
-
return Promise.resolve(this.cache.size());
|
|
1499
|
-
}
|
|
1500
|
-
}
|
|
1501
|
-
var simpleCacheStore_default = SimpleCacheStore;
|
|
1502
|
-
|
|
1503
|
-
// ../../src/core/cache/createCacheStore.ts
|
|
1504
|
-
function createCacheStore(options) {
|
|
1505
|
-
if (options.driver === "redis") {
|
|
1506
|
-
if (!options.redisUrl) {
|
|
1507
|
-
throw new Error('CACHE_DRIVER="redis" requires REDIS_URL to be set.');
|
|
1508
|
-
}
|
|
1509
|
-
return new redisCacheStore_default(options.redisUrl, options.ttlMs, options.maxEntries);
|
|
1510
|
-
}
|
|
1511
|
-
return new simpleCacheStore_default(new simpleCache_default(options.ttlMs, options.maxEntries));
|
|
1512
|
-
}
|
|
1012
|
+
// ../../src/bootstrap/providers/cache.ts
|
|
1013
|
+
import { createCacheStore } from "@getstrata/core/cache/createCacheStore";
|
|
1513
1014
|
|
|
1514
1015
|
// ../../src/core/cache/taggedCache.ts
|
|
1515
1016
|
class TaggedCache {
|
|
@@ -1587,6 +1088,9 @@ var cacheProvider = {
|
|
|
1587
1088
|
};
|
|
1588
1089
|
var cache_default = cacheProvider;
|
|
1589
1090
|
|
|
1091
|
+
// ../../src/bootstrap/providers/config.ts
|
|
1092
|
+
import { validateEnv } from "@getstrata/core/config/envSchema";
|
|
1093
|
+
|
|
1590
1094
|
// ../../src/config/app.ts
|
|
1591
1095
|
var appConfig = {
|
|
1592
1096
|
name: "WorkHub",
|
|
@@ -1603,34 +1107,6 @@ var queueConfig = {
|
|
|
1603
1107
|
backoffMs: Number(process.env.QUEUE_BACKOFF_MS ?? "1000")
|
|
1604
1108
|
};
|
|
1605
1109
|
|
|
1606
|
-
// ../../src/core/config/envSchema.ts
|
|
1607
|
-
function validateEnv(schema, env = process.env) {
|
|
1608
|
-
const resolved = {};
|
|
1609
|
-
for (const [name, rule] of Object.entries(schema)) {
|
|
1610
|
-
const rawValue = env[name];
|
|
1611
|
-
const value = rawValue === undefined || rawValue.trim() === "" ? rule.default : rawValue;
|
|
1612
|
-
if (value === undefined || value.trim() === "") {
|
|
1613
|
-
if (rule.required) {
|
|
1614
|
-
throw new Error(`Missing required environment variable "${name}".`);
|
|
1615
|
-
}
|
|
1616
|
-
continue;
|
|
1617
|
-
}
|
|
1618
|
-
if (rule.integer) {
|
|
1619
|
-
const parsed = Number.parseInt(value, 10);
|
|
1620
|
-
const minimum = rule.minimum ?? Number.NEGATIVE_INFINITY;
|
|
1621
|
-
if (!Number.isInteger(parsed) || parsed < minimum) {
|
|
1622
|
-
const comparison = minimum === Number.NEGATIVE_INFINITY ? "an integer" : `an integer >= ${minimum}`;
|
|
1623
|
-
throw new Error(`Environment variable "${name}" must be ${comparison}.`);
|
|
1624
|
-
}
|
|
1625
|
-
}
|
|
1626
|
-
if (rule.pattern && !rule.pattern.test(value)) {
|
|
1627
|
-
throw new Error(`Environment variable "${name}" has an invalid format.`);
|
|
1628
|
-
}
|
|
1629
|
-
resolved[name] = value;
|
|
1630
|
-
}
|
|
1631
|
-
return resolved;
|
|
1632
|
-
}
|
|
1633
|
-
|
|
1634
1110
|
// ../../src/bootstrap/env.ts
|
|
1635
1111
|
import { defineEnvSchema } from "@getstrata/core/config/envSchema";
|
|
1636
1112
|
var appEnvSchema = defineEnvSchema({
|
|
@@ -1750,39 +1226,8 @@ var configProvider = {
|
|
|
1750
1226
|
};
|
|
1751
1227
|
var config_default = configProvider;
|
|
1752
1228
|
|
|
1753
|
-
// ../../src/core/events/eventBus.ts
|
|
1754
|
-
class EventBus {
|
|
1755
|
-
constructor() {}
|
|
1756
|
-
listeners = new Map;
|
|
1757
|
-
listen(event, listener) {
|
|
1758
|
-
const handlers = this.listeners.get(event) ?? new Set;
|
|
1759
|
-
handlers.add(listener);
|
|
1760
|
-
this.listeners.set(event, handlers);
|
|
1761
|
-
return () => {
|
|
1762
|
-
handlers.delete(listener);
|
|
1763
|
-
if (handlers.size === 0) {
|
|
1764
|
-
this.listeners.delete(event);
|
|
1765
|
-
}
|
|
1766
|
-
};
|
|
1767
|
-
}
|
|
1768
|
-
async dispatch(event, payload) {
|
|
1769
|
-
const handlers = this.listeners.get(event);
|
|
1770
|
-
if (!handlers || handlers.size === 0) {
|
|
1771
|
-
return;
|
|
1772
|
-
}
|
|
1773
|
-
for (const handler of handlers) {
|
|
1774
|
-
await handler(payload);
|
|
1775
|
-
}
|
|
1776
|
-
}
|
|
1777
|
-
}
|
|
1778
|
-
var eventBus = new EventBus;
|
|
1779
|
-
|
|
1780
|
-
// ../../src/core/events/index.ts
|
|
1781
|
-
function modelEventName(tableName, action) {
|
|
1782
|
-
return `${tableName}.${action}`;
|
|
1783
|
-
}
|
|
1784
|
-
|
|
1785
1229
|
// ../../src/bootstrap/providers/events.ts
|
|
1230
|
+
import { eventBus } from "@getstrata/core/events";
|
|
1786
1231
|
var eventsProvider = {
|
|
1787
1232
|
name: "core.events",
|
|
1788
1233
|
register({ container }) {
|
|
@@ -1819,14 +1264,14 @@ function discoverListeners() {
|
|
|
1819
1264
|
}
|
|
1820
1265
|
|
|
1821
1266
|
// ../../src/bootstrap/listeners/invalidateCacheOnModelWrite.ts
|
|
1822
|
-
import { eventBus as eventBus2, modelEventName
|
|
1267
|
+
import { eventBus as eventBus2, modelEventName } from "@getstrata/core/events";
|
|
1823
1268
|
import InvalidateCacheTagsJob from "@getstrata/core/jobs/invalidateCacheTagsJob";
|
|
1824
1269
|
import { createTrackedJob } from "@getstrata/core/queue/createAppQueue";
|
|
1825
1270
|
var MODEL_WRITE_ACTIONS = ["created", "updated", "deleted", "restored", "force-deleted"];
|
|
1826
1271
|
function registerInvalidateCacheOnModelWriteListeners(bus = eventBus2) {
|
|
1827
1272
|
for (const tableName of discoverModelTableNames()) {
|
|
1828
1273
|
for (const action of MODEL_WRITE_ACTIONS) {
|
|
1829
|
-
bus.listen(
|
|
1274
|
+
bus.listen(modelEventName(tableName, action), async () => {
|
|
1830
1275
|
const tags = cacheTagsForModelWrite(tableName, action);
|
|
1831
1276
|
if (tags.length === 0) {
|
|
1832
1277
|
return;
|
|
@@ -1868,46 +1313,8 @@ var listenersProvider = {
|
|
|
1868
1313
|
};
|
|
1869
1314
|
var listeners_default = listenersProvider;
|
|
1870
1315
|
|
|
1871
|
-
// ../../src/core/auth/policy.ts
|
|
1872
|
-
var BLOCKED_POLICY_ACTIONS = new Set([
|
|
1873
|
-
"constructor",
|
|
1874
|
-
"toString",
|
|
1875
|
-
"valueOf",
|
|
1876
|
-
"hasOwnProperty",
|
|
1877
|
-
"isPrototypeOf",
|
|
1878
|
-
"propertyIsEnumerable",
|
|
1879
|
-
"__proto__"
|
|
1880
|
-
]);
|
|
1881
|
-
|
|
1882
|
-
class PolicyGate {
|
|
1883
|
-
constructor() {}
|
|
1884
|
-
policies = new Map;
|
|
1885
|
-
register(resource, policy) {
|
|
1886
|
-
this.policies.set(resource, policy);
|
|
1887
|
-
}
|
|
1888
|
-
allows(resource, action, user, model) {
|
|
1889
|
-
const policy = this.policies.get(resource);
|
|
1890
|
-
if (!policy) {
|
|
1891
|
-
return false;
|
|
1892
|
-
}
|
|
1893
|
-
if (BLOCKED_POLICY_ACTIONS.has(action) || !(action in policy)) {
|
|
1894
|
-
return false;
|
|
1895
|
-
}
|
|
1896
|
-
const handler = policy[action];
|
|
1897
|
-
if (typeof handler !== "function") {
|
|
1898
|
-
return false;
|
|
1899
|
-
}
|
|
1900
|
-
const resolvedUser = user === undefined ? currentAuthUser() : user;
|
|
1901
|
-
return model === undefined ? handler.call(policy, resolvedUser) : handler.call(policy, resolvedUser, model);
|
|
1902
|
-
}
|
|
1903
|
-
authorize(resource, action, user, model) {
|
|
1904
|
-
if (!this.allows(resource, action, user, model)) {
|
|
1905
|
-
throw new ForbiddenError2;
|
|
1906
|
-
}
|
|
1907
|
-
}
|
|
1908
|
-
}
|
|
1909
|
-
|
|
1910
1316
|
// ../../src/bootstrap/providers/policy.ts
|
|
1317
|
+
import { PolicyGate } from "@getstrata/core/auth/policy";
|
|
1911
1318
|
var policyProvider = {
|
|
1912
1319
|
name: "core.policy",
|
|
1913
1320
|
register({ container }) {
|
|
@@ -1916,2553 +1323,52 @@ var policyProvider = {
|
|
|
1916
1323
|
};
|
|
1917
1324
|
var policy_default = policyProvider;
|
|
1918
1325
|
|
|
1919
|
-
// ../../src/
|
|
1920
|
-
|
|
1921
|
-
|
|
1922
|
-
|
|
1923
|
-
|
|
1924
|
-
|
|
1925
|
-
total: input.total,
|
|
1926
|
-
last_page: lastPage
|
|
1927
|
-
};
|
|
1928
|
-
}
|
|
1326
|
+
// ../../src/bootstrap/providers/queue.ts
|
|
1327
|
+
import {
|
|
1328
|
+
createAppQueue,
|
|
1329
|
+
createFailedJobService,
|
|
1330
|
+
FAILED_JOB_SERVICE_TOKEN
|
|
1331
|
+
} from "@getstrata/core/queue/createAppQueue";
|
|
1929
1332
|
|
|
1930
|
-
// ../../src/
|
|
1931
|
-
|
|
1932
|
-
|
|
1333
|
+
// ../../src/bootstrap/queue/defaultJobs.ts
|
|
1334
|
+
import DispatchWebhookJob from "@getstrata/core/jobs/dispatchWebhookJob";
|
|
1335
|
+
import InvalidateCacheTagsJob2 from "@getstrata/core/jobs/invalidateCacheTagsJob";
|
|
1336
|
+
import { jobRegistry } from "@getstrata/core/queue/jobRegistry";
|
|
1337
|
+
import { resolveApplicationCache as resolveApplicationCache2 } from "@getstrata/core/runtime/applicationRegistry";
|
|
1338
|
+
function registerDefaultJobs() {
|
|
1339
|
+
jobRegistry.register("cache.invalidate-tags", () => {
|
|
1340
|
+
return new InvalidateCacheTagsJob2(resolveApplicationCache2());
|
|
1341
|
+
});
|
|
1342
|
+
jobRegistry.register("webhook.dispatch", () => new DispatchWebhookJob);
|
|
1933
1343
|
}
|
|
1934
|
-
|
|
1935
|
-
|
|
1936
|
-
|
|
1344
|
+
|
|
1345
|
+
// ../../src/bootstrap/providers/queue.ts
|
|
1346
|
+
var queueProvider = {
|
|
1347
|
+
name: "core.queue",
|
|
1348
|
+
register({ container, config }) {
|
|
1349
|
+
const configuredDriver = process.env.QUEUE_DRIVER ?? DEFAULT_QUEUE_DRIVER;
|
|
1350
|
+
const driver = configuredDriver === "async" || configuredDriver === "redis" || configuredDriver === "sync" ? configuredDriver : DEFAULT_QUEUE_DRIVER;
|
|
1351
|
+
config.set("queue.driver", driver);
|
|
1352
|
+
const failedJobs = createFailedJobService();
|
|
1353
|
+
container.set(FAILED_JOB_SERVICE_TOKEN, failedJobs);
|
|
1354
|
+
container.set(CORE_QUEUE_TOKEN, createAppQueue(driver, config.get(REDIS_URL_CONFIG_KEY) ?? process.env.REDIS_URL, failedJobs, registerDefaultJobs));
|
|
1937
1355
|
}
|
|
1938
|
-
|
|
1939
|
-
|
|
1940
|
-
|
|
1941
|
-
|
|
1942
|
-
|
|
1943
|
-
|
|
1944
|
-
|
|
1945
|
-
}
|
|
1946
|
-
|
|
1947
|
-
if (error instanceof HttpError) {
|
|
1948
|
-
return error;
|
|
1949
|
-
}
|
|
1950
|
-
if (!isPostgresError(error)) {
|
|
1951
|
-
const message = error instanceof Error ? error.message : "Database operation failed.";
|
|
1952
|
-
return new BadRequestError(message);
|
|
1953
|
-
}
|
|
1954
|
-
const sqlState = getPostgresSqlState(error);
|
|
1955
|
-
switch (sqlState) {
|
|
1956
|
-
case "23505":
|
|
1957
|
-
return new ConflictError(error.detail ?? "A record with these values already exists.", {
|
|
1958
|
-
constraint: error.constraint
|
|
1959
|
-
});
|
|
1960
|
-
case "23503":
|
|
1961
|
-
return new UnprocessableEntityError(error.detail ?? "Referenced record does not exist.", {
|
|
1962
|
-
constraint: error.constraint
|
|
1963
|
-
});
|
|
1964
|
-
case "23502":
|
|
1965
|
-
return new BadRequestError(error.detail ?? "Required field is missing.", {
|
|
1966
|
-
constraint: error.constraint
|
|
1967
|
-
});
|
|
1968
|
-
case "23514":
|
|
1969
|
-
return new BadRequestError(error.detail ?? "Value violates a database constraint.", {
|
|
1970
|
-
constraint: error.constraint
|
|
1971
|
-
});
|
|
1972
|
-
default:
|
|
1973
|
-
return new BadRequestError(error.message ?? "Database operation failed.", {
|
|
1974
|
-
code: error.code,
|
|
1975
|
-
sqlState
|
|
1976
|
-
});
|
|
1977
|
-
}
|
|
1978
|
-
}
|
|
1979
|
-
async function withDatabaseErrorHandling(operation) {
|
|
1980
|
-
try {
|
|
1981
|
-
return await operation();
|
|
1982
|
-
} catch (error) {
|
|
1983
|
-
throw mapDatabaseError(error);
|
|
1984
|
-
}
|
|
1985
|
-
}
|
|
1986
|
-
|
|
1987
|
-
// ../../src/core/database/query.ts
|
|
1988
|
-
function quoteIdentifier(identifier) {
|
|
1989
|
-
if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(identifier)) {
|
|
1990
|
-
throw new Error(`Invalid SQL identifier: ${identifier}`);
|
|
1991
|
-
}
|
|
1992
|
-
return `"${identifier}"`;
|
|
1993
|
-
}
|
|
1994
|
-
function qualifyColumn(tableName, column) {
|
|
1995
|
-
return `${quoteIdentifier(tableName)}.${quoteIdentifier(column)}`;
|
|
1996
|
-
}
|
|
1997
|
-
function resolveQualifiedColumn(defaultTable, columnName) {
|
|
1998
|
-
if (columnName.includes(".")) {
|
|
1999
|
-
const [table, column] = columnName.split(".", 2);
|
|
2000
|
-
if (!table || !column) {
|
|
2001
|
-
throw new Error(`Invalid qualified column: ${columnName}`);
|
|
2002
|
-
}
|
|
2003
|
-
return qualifyColumn(table, column);
|
|
2004
|
-
}
|
|
2005
|
-
return qualifyColumn(defaultTable, columnName);
|
|
2006
|
-
}
|
|
2007
|
-
function parseQualifiedColumn(reference) {
|
|
2008
|
-
const [table, column] = reference.split(".", 2);
|
|
2009
|
-
if (!table || !column) {
|
|
2010
|
-
throw new Error(`Join columns must be qualified as table.column: ${reference}`);
|
|
2011
|
-
}
|
|
2012
|
-
return { table, column };
|
|
2013
|
-
}
|
|
2014
|
-
function normalizeDirection(direction = "ASC") {
|
|
2015
|
-
return direction.toUpperCase() === "DESC" ? "DESC" : "ASC";
|
|
2016
|
-
}
|
|
2017
|
-
function isQueryOperator(value) {
|
|
2018
|
-
return value !== null && !Array.isArray(value) && !(value instanceof Date) && typeof value === "object";
|
|
2019
|
-
}
|
|
2020
|
-
function pushParam(values, value) {
|
|
2021
|
-
values.push(value);
|
|
2022
|
-
return `$${values.length}`;
|
|
2023
|
-
}
|
|
2024
|
-
function buildInClause(column, values, params) {
|
|
2025
|
-
if (values.length === 0) {
|
|
2026
|
-
return "1 = 0";
|
|
2027
|
-
}
|
|
2028
|
-
const placeholders = values.map((value) => pushParam(params, value)).join(", ");
|
|
2029
|
-
return `${column} IN (${placeholders})`;
|
|
2030
|
-
}
|
|
2031
|
-
function buildOperatorClauses(column, operator, params) {
|
|
2032
|
-
const clauses = [];
|
|
2033
|
-
if (operator.isNull === true) {
|
|
2034
|
-
clauses.push(`${column} IS NULL`);
|
|
2035
|
-
}
|
|
2036
|
-
if (operator.isNull === false) {
|
|
2037
|
-
clauses.push(`${column} IS NOT NULL`);
|
|
2038
|
-
}
|
|
2039
|
-
if (operator.eq !== undefined) {
|
|
2040
|
-
if (operator.eq === null) {
|
|
2041
|
-
clauses.push(`${column} IS NULL`);
|
|
2042
|
-
} else {
|
|
2043
|
-
clauses.push(`${column} = ${pushParam(params, operator.eq)}`);
|
|
2044
|
-
}
|
|
2045
|
-
}
|
|
2046
|
-
if (operator.in !== undefined) {
|
|
2047
|
-
clauses.push(buildInClause(column, operator.in, params));
|
|
2048
|
-
}
|
|
2049
|
-
if (operator.gt !== undefined) {
|
|
2050
|
-
clauses.push(`${column} > ${pushParam(params, operator.gt)}`);
|
|
2051
|
-
}
|
|
2052
|
-
if (operator.gte !== undefined) {
|
|
2053
|
-
clauses.push(`${column} >= ${pushParam(params, operator.gte)}`);
|
|
2054
|
-
}
|
|
2055
|
-
if (operator.lt !== undefined) {
|
|
2056
|
-
clauses.push(`${column} < ${pushParam(params, operator.lt)}`);
|
|
2057
|
-
}
|
|
2058
|
-
if (operator.lte !== undefined) {
|
|
2059
|
-
clauses.push(`${column} <= ${pushParam(params, operator.lte)}`);
|
|
2060
|
-
}
|
|
2061
|
-
if (operator.ilike !== undefined) {
|
|
2062
|
-
clauses.push(`${column} ILIKE ${pushParam(params, `%${operator.ilike}%`)}`);
|
|
2063
|
-
}
|
|
2064
|
-
if (operator.tsMatch !== undefined) {
|
|
2065
|
-
clauses.push(`${column} @@ plainto_tsquery('english', ${pushParam(params, operator.tsMatch)})`);
|
|
2066
|
-
}
|
|
2067
|
-
return clauses;
|
|
2068
|
-
}
|
|
2069
|
-
function appendWhereParts(tableName, where, params) {
|
|
2070
|
-
const clauses = [];
|
|
2071
|
-
for (const [columnName, filterValue] of Object.entries(where)) {
|
|
2072
|
-
if (filterValue === undefined) {
|
|
2073
|
-
continue;
|
|
2074
|
-
}
|
|
2075
|
-
const column = resolveQualifiedColumn(tableName, columnName);
|
|
2076
|
-
if (Array.isArray(filterValue)) {
|
|
2077
|
-
clauses.push(buildInClause(column, filterValue, params));
|
|
2078
|
-
continue;
|
|
2079
|
-
}
|
|
2080
|
-
if (isQueryOperator(filterValue)) {
|
|
2081
|
-
clauses.push(...buildOperatorClauses(column, filterValue, params));
|
|
2082
|
-
continue;
|
|
2083
|
-
}
|
|
2084
|
-
if (filterValue === null) {
|
|
2085
|
-
clauses.push(`${column} IS NULL`);
|
|
2086
|
-
continue;
|
|
2087
|
-
}
|
|
2088
|
-
clauses.push(`${column} = ${pushParam(params, filterValue)}`);
|
|
2089
|
-
}
|
|
2090
|
-
return clauses.join(" AND ");
|
|
2091
|
-
}
|
|
2092
|
-
function buildWhereNodeClause(tableName, node, params) {
|
|
2093
|
-
if ("where" in node) {
|
|
2094
|
-
return appendWhereParts(tableName, node.where, params);
|
|
2095
|
-
}
|
|
2096
|
-
const grouped = buildWhereGroupClause(tableName, node.group, params);
|
|
2097
|
-
if (!grouped) {
|
|
2098
|
-
return "";
|
|
2099
|
-
}
|
|
2100
|
-
return grouped.includes(" OR ") ? `(${grouped})` : grouped;
|
|
2101
|
-
}
|
|
2102
|
-
function buildWhereGroupClause(tableName, nodes, params) {
|
|
2103
|
-
let result = "";
|
|
2104
|
-
for (const node of nodes) {
|
|
2105
|
-
const part = buildWhereNodeClause(tableName, node, params);
|
|
2106
|
-
if (!part) {
|
|
2107
|
-
continue;
|
|
2108
|
-
}
|
|
2109
|
-
if (!result) {
|
|
2110
|
-
result = part;
|
|
2111
|
-
continue;
|
|
2112
|
-
}
|
|
2113
|
-
result = node.kind === "or" ? `${result} OR ${part}` : `${result} AND ${part}`;
|
|
2114
|
-
}
|
|
2115
|
-
if (!result) {
|
|
2116
|
-
return "";
|
|
2117
|
-
}
|
|
2118
|
-
return result;
|
|
2119
|
-
}
|
|
2120
|
-
function buildAdvancedWhereClause(tableName, where = {}, whereNodes = [], params = []) {
|
|
2121
|
-
const nodes = [];
|
|
2122
|
-
if (Object.keys(where).length > 0) {
|
|
2123
|
-
nodes.push({ kind: "and", where });
|
|
2124
|
-
}
|
|
2125
|
-
nodes.push(...whereNodes);
|
|
2126
|
-
const combined = buildWhereGroupClause(tableName, nodes, params);
|
|
2127
|
-
return {
|
|
2128
|
-
clause: combined ? ` WHERE ${combined}` : "",
|
|
2129
|
-
params
|
|
2130
|
-
};
|
|
2131
|
-
}
|
|
2132
|
-
function resolveSoftDeleteColumn(table) {
|
|
2133
|
-
if (!table.softDeletes) {
|
|
2134
|
-
return null;
|
|
2135
|
-
}
|
|
2136
|
-
if (table.softDeletes === true) {
|
|
2137
|
-
return "deleted_at";
|
|
2138
|
-
}
|
|
2139
|
-
return table.softDeletes.column ?? "deleted_at";
|
|
2140
|
-
}
|
|
2141
|
-
function appendSoftDeleteScope(table, options, clauses) {
|
|
2142
|
-
const column = resolveSoftDeleteColumn(table);
|
|
2143
|
-
if (!column) {
|
|
2144
|
-
return;
|
|
2145
|
-
}
|
|
2146
|
-
const qualifiedColumn = qualifyColumn(table.name, column);
|
|
2147
|
-
if (options.onlyTrashed) {
|
|
2148
|
-
clauses.push(`${qualifiedColumn} IS NOT NULL`);
|
|
2149
|
-
return;
|
|
2150
|
-
}
|
|
2151
|
-
if (!options.withTrashed) {
|
|
2152
|
-
clauses.push(`${qualifiedColumn} IS NULL`);
|
|
2153
|
-
}
|
|
2154
|
-
}
|
|
2155
|
-
function buildQueryWhereClause(table, options = {}, whereNodes = [], params = []) {
|
|
2156
|
-
const { clause, params: whereParams } = buildAdvancedWhereClause(table.name, options.where ?? {}, whereNodes, params);
|
|
2157
|
-
const softDeleteClauses = [];
|
|
2158
|
-
appendSoftDeleteScope(table, options, softDeleteClauses);
|
|
2159
|
-
if (softDeleteClauses.length === 0) {
|
|
2160
|
-
return { clause, params: whereParams };
|
|
2161
|
-
}
|
|
2162
|
-
const base = clause.replace(/^ WHERE /, "");
|
|
2163
|
-
const scope = softDeleteClauses.join(" AND ");
|
|
2164
|
-
return {
|
|
2165
|
-
clause: base ? ` WHERE (${base}) AND ${scope}` : ` WHERE ${scope}`,
|
|
2166
|
-
params: whereParams
|
|
2167
|
-
};
|
|
2168
|
-
}
|
|
2169
|
-
function isQueryOrder(value) {
|
|
2170
|
-
return "column" in value;
|
|
2171
|
-
}
|
|
2172
|
-
function normalizeOrderBy(orderBy) {
|
|
2173
|
-
if (!orderBy) {
|
|
2174
|
-
return [];
|
|
2175
|
-
}
|
|
2176
|
-
if (Array.isArray(orderBy)) {
|
|
2177
|
-
return orderBy;
|
|
2178
|
-
}
|
|
2179
|
-
if (isQueryOrder(orderBy)) {
|
|
2180
|
-
return [orderBy];
|
|
2181
|
-
}
|
|
2182
|
-
return Object.entries(orderBy).map(([column, direction]) => ({
|
|
2183
|
-
column,
|
|
2184
|
-
direction
|
|
2185
|
-
}));
|
|
2186
|
-
}
|
|
2187
|
-
function buildOrderByClause(tableName, orderBy) {
|
|
2188
|
-
const parts = normalizeOrderBy(orderBy).map(({ column, direction }) => {
|
|
2189
|
-
return `${resolveQualifiedColumn(tableName, column)} ${normalizeDirection(direction)}`;
|
|
2190
|
-
});
|
|
2191
|
-
return parts.length > 0 ? ` ORDER BY ${parts.join(", ")}` : "";
|
|
2192
|
-
}
|
|
2193
|
-
function buildGroupByClause(tableName, groupBy) {
|
|
2194
|
-
if (!groupBy) {
|
|
2195
|
-
return "";
|
|
2196
|
-
}
|
|
2197
|
-
const columns = (Array.isArray(groupBy) ? groupBy : [groupBy]).map((column) => String(column));
|
|
2198
|
-
const parts = columns.map((column) => resolveQualifiedColumn(tableName, column));
|
|
2199
|
-
return parts.length > 0 ? ` GROUP BY ${parts.join(", ")}` : "";
|
|
2200
|
-
}
|
|
2201
|
-
function buildHavingClause(tableName, having, params) {
|
|
2202
|
-
if (!having) {
|
|
2203
|
-
return "";
|
|
2204
|
-
}
|
|
2205
|
-
const body = appendWhereParts(tableName, having, params);
|
|
2206
|
-
return body.length > 0 ? ` HAVING ${body}` : "";
|
|
2207
|
-
}
|
|
2208
|
-
function buildJoinClause(joins = []) {
|
|
2209
|
-
return joins.map((join3) => {
|
|
2210
|
-
const joinType = join3.type === "left" ? "LEFT JOIN" : "INNER JOIN";
|
|
2211
|
-
const onClause = join3.on.map(({ left, right }) => `${qualifyColumn(left.table, left.column)} = ${qualifyColumn(right.table, right.column)}`).join(" AND ");
|
|
2212
|
-
return ` ${joinType} ${quoteIdentifier(join3.table)} ON ${onClause}`;
|
|
2213
|
-
}).join("");
|
|
2214
|
-
}
|
|
2215
|
-
function buildLimitClause(limit) {
|
|
2216
|
-
if (limit === undefined) {
|
|
2217
|
-
return "";
|
|
2218
|
-
}
|
|
2219
|
-
if (!Number.isInteger(limit) || limit <= 0) {
|
|
2220
|
-
throw new Error("Query limit must be a positive integer.");
|
|
2221
|
-
}
|
|
2222
|
-
return ` LIMIT ${limit}`;
|
|
2223
|
-
}
|
|
2224
|
-
function buildOffsetClause(offset) {
|
|
2225
|
-
if (offset === undefined) {
|
|
2226
|
-
return "";
|
|
2227
|
-
}
|
|
2228
|
-
if (!Number.isInteger(offset) || offset < 0) {
|
|
2229
|
-
throw new Error("Query offset must be a non-negative integer.");
|
|
2230
|
-
}
|
|
2231
|
-
return ` OFFSET ${offset}`;
|
|
2232
|
-
}
|
|
2233
|
-
function buildReturningColumns(table) {
|
|
2234
|
-
return table.columns.map((column) => qualifyColumn(table.name, column)).join(", ");
|
|
2235
|
-
}
|
|
2236
|
-
function buildSelectList(table, select, params = []) {
|
|
2237
|
-
if (!select || select.length === 0) {
|
|
2238
|
-
return buildReturningColumns(table);
|
|
2239
|
-
}
|
|
2240
|
-
return select.map((item) => {
|
|
2241
|
-
if (item.kind === "column") {
|
|
2242
|
-
const column2 = qualifyColumn(item.table, item.column);
|
|
2243
|
-
return item.as ? `${column2} AS ${quoteIdentifier(item.as)}` : column2;
|
|
2244
|
-
}
|
|
2245
|
-
if (item.kind === "literalText") {
|
|
2246
|
-
return `${pushParam(params, item.value)}::text AS ${quoteIdentifier(item.as)}`;
|
|
2247
|
-
}
|
|
2248
|
-
const column = qualifyColumn(item.table, item.column);
|
|
2249
|
-
const placeholder = pushParam(params, item.query);
|
|
2250
|
-
return `ts_rank(${column}, plainto_tsquery('english', ${placeholder})) AS ${quoteIdentifier(item.as)}`;
|
|
2251
|
-
}).join(", ");
|
|
2252
|
-
}
|
|
2253
|
-
function getDefinedColumnEntries(table, values, options = {}) {
|
|
2254
|
-
const record = values;
|
|
2255
|
-
const excluded = new Set(options.exclude ?? []);
|
|
2256
|
-
return table.columns.flatMap((column) => {
|
|
2257
|
-
if (excluded.has(column) || !Object.hasOwn(record, column)) {
|
|
2258
|
-
return [];
|
|
2259
|
-
}
|
|
2260
|
-
const value = record[column];
|
|
2261
|
-
if (value === undefined) {
|
|
2262
|
-
return [];
|
|
2263
|
-
}
|
|
2264
|
-
return [[column, value]];
|
|
2265
|
-
});
|
|
2266
|
-
}
|
|
2267
|
-
function buildSelectQuery(table, options = {}, whereNodes = []) {
|
|
2268
|
-
const params = [];
|
|
2269
|
-
const columns = buildSelectList(table, options.select, params);
|
|
2270
|
-
const { clause } = buildQueryWhereClause(table, options, whereNodes, params);
|
|
2271
|
-
const joins = buildJoinClause(options.joins);
|
|
2272
|
-
const groupBy = buildGroupByClause(table.name, options.groupBy);
|
|
2273
|
-
const havingClause = buildHavingClause(table.name, options.having, params);
|
|
2274
|
-
const orderBy = buildOrderByClause(table.name, options.orderBy ?? table.defaultOrderBy);
|
|
2275
|
-
const limit = buildLimitClause(options.limit);
|
|
2276
|
-
const offset = buildOffsetClause(options.offset);
|
|
2277
|
-
return {
|
|
2278
|
-
text: `SELECT ${columns} FROM ${quoteIdentifier(table.name)}${joins}${clause}${groupBy}${havingClause}${orderBy}${limit}${offset}`,
|
|
2279
|
-
params
|
|
2280
|
-
};
|
|
2281
|
-
}
|
|
2282
|
-
function buildCountQuery(table, where = {}, options = {}, whereNodes = []) {
|
|
2283
|
-
const params = [];
|
|
2284
|
-
const { clause, params: whereParams } = buildQueryWhereClause(table, {
|
|
2285
|
-
where,
|
|
2286
|
-
withTrashed: options.withTrashed,
|
|
2287
|
-
onlyTrashed: options.onlyTrashed
|
|
2288
|
-
}, whereNodes);
|
|
2289
|
-
params.push(...whereParams);
|
|
2290
|
-
const joins = buildJoinClause(options.joins);
|
|
2291
|
-
const groupBy = buildGroupByClause(table.name, options.groupBy);
|
|
2292
|
-
return {
|
|
2293
|
-
text: `SELECT COUNT(*) AS count FROM ${quoteIdentifier(table.name)}${joins}${clause}${groupBy}`,
|
|
2294
|
-
params
|
|
2295
|
-
};
|
|
2296
|
-
}
|
|
2297
|
-
function buildProjectionQuery(table, expression, alias, options = {}, whereNodes = []) {
|
|
2298
|
-
assertSafeProjectionExpression(expression);
|
|
2299
|
-
const params = [];
|
|
2300
|
-
const { clause, params: whereParams } = buildQueryWhereClause(table, options, whereNodes);
|
|
2301
|
-
params.push(...whereParams);
|
|
2302
|
-
const joins = buildJoinClause(options.joins);
|
|
2303
|
-
const groupBy = buildGroupByClause(table.name, options.groupBy);
|
|
2304
|
-
const orderBy = buildOrderByClause(table.name, options.orderBy);
|
|
2305
|
-
const limit = buildLimitClause(options.limit);
|
|
2306
|
-
return {
|
|
2307
|
-
text: `SELECT ${expression} AS ${quoteIdentifier(alias)} FROM ${quoteIdentifier(table.name)}${joins}${clause}${groupBy}${orderBy}${limit}`,
|
|
2308
|
-
params
|
|
2309
|
-
};
|
|
2310
|
-
}
|
|
2311
|
-
var SAFE_PROJECTION_EXPRESSION = /^(COUNT\(\*\)|(?:"[\w_]+"(?:\."[\w_]+")?)|(?:AVG|SUM|MIN|MAX)\((?:"[\w_]+"(?:\."[\w_]+")?)\))$/;
|
|
2312
|
-
function assertSafeProjectionExpression(expression) {
|
|
2313
|
-
if (!SAFE_PROJECTION_EXPRESSION.test(expression.trim())) {
|
|
2314
|
-
throw new Error(`Unsafe projection expression: ${expression}`);
|
|
2315
|
-
}
|
|
2316
|
-
}
|
|
2317
|
-
function buildGroupedCountQuery(table, column, where = {}, options = {}) {
|
|
2318
|
-
const qualifiedColumn = qualifyColumn(table.name, column);
|
|
2319
|
-
const { clause, params } = buildQueryWhereClause(table, {
|
|
2320
|
-
where,
|
|
2321
|
-
...options
|
|
2322
|
-
});
|
|
2323
|
-
return {
|
|
2324
|
-
text: `SELECT ${qualifiedColumn} AS ${quoteIdentifier("value")}, COUNT(*) AS ${quoteIdentifier("count")} FROM ${quoteIdentifier(table.name)}${clause} GROUP BY ${qualifiedColumn} ORDER BY ${qualifiedColumn} ASC`,
|
|
2325
|
-
params
|
|
2326
|
-
};
|
|
2327
|
-
}
|
|
2328
|
-
function buildInsertQuery(table, values) {
|
|
2329
|
-
const entries = getDefinedColumnEntries(table, values);
|
|
2330
|
-
if (entries.length === 0) {
|
|
2331
|
-
throw new Error(`Cannot insert into ${table.name} without any column values.`);
|
|
2332
|
-
}
|
|
2333
|
-
const params = [];
|
|
2334
|
-
const columns = entries.map(([column]) => quoteIdentifier(column)).join(", ");
|
|
2335
|
-
const placeholders = entries.map(([, value]) => pushParam(params, value)).join(", ");
|
|
2336
|
-
const returningColumns = buildReturningColumns(table);
|
|
2337
|
-
return {
|
|
2338
|
-
text: `INSERT INTO ${quoteIdentifier(table.name)} (${columns}) VALUES (${placeholders}) RETURNING ${returningColumns}`,
|
|
2339
|
-
params
|
|
2340
|
-
};
|
|
2341
|
-
}
|
|
2342
|
-
function buildUpdateQuery(table, id, changes) {
|
|
2343
|
-
const entries = getDefinedColumnEntries(table, changes, {
|
|
2344
|
-
exclude: [table.primaryKey]
|
|
2345
|
-
});
|
|
2346
|
-
if (entries.length === 0) {
|
|
2347
|
-
throw new Error(`Cannot update ${table.name} without any changed column values.`);
|
|
2348
|
-
}
|
|
2349
|
-
const params = [];
|
|
2350
|
-
const setClause = entries.map(([column, value]) => `${quoteIdentifier(column)} = ${pushParam(params, value)}`).join(", ");
|
|
2351
|
-
const primaryKeyPlaceholder = pushParam(params, id);
|
|
2352
|
-
const returningColumns = buildReturningColumns(table);
|
|
2353
|
-
const scopeClauses = [];
|
|
2354
|
-
appendSoftDeleteScope(table, {}, scopeClauses);
|
|
2355
|
-
const scopeSuffix = scopeClauses.length > 0 ? ` AND ${scopeClauses.join(" AND ")}` : "";
|
|
2356
|
-
return {
|
|
2357
|
-
text: `UPDATE ${quoteIdentifier(table.name)} SET ${setClause} WHERE ${quoteIdentifier(table.primaryKey)} = ${primaryKeyPlaceholder}${scopeSuffix} RETURNING ${returningColumns}`,
|
|
2358
|
-
params
|
|
2359
|
-
};
|
|
2360
|
-
}
|
|
2361
|
-
function buildSoftDeleteByIdQuery(table, id, deletedAt) {
|
|
2362
|
-
const deletedAtColumn = resolveSoftDeleteColumn(table);
|
|
2363
|
-
if (!deletedAtColumn) {
|
|
2364
|
-
throw new Error(`Table ${table.name} does not support soft deletes.`);
|
|
2365
|
-
}
|
|
2366
|
-
const returningColumns = buildReturningColumns(table);
|
|
2367
|
-
const scopeClauses = [];
|
|
2368
|
-
appendSoftDeleteScope(table, {}, scopeClauses);
|
|
2369
|
-
const scopeSuffix = scopeClauses.length > 0 ? ` AND ${scopeClauses.join(" AND ")}` : "";
|
|
2370
|
-
return {
|
|
2371
|
-
text: `UPDATE ${quoteIdentifier(table.name)} SET ${quoteIdentifier(deletedAtColumn)} = $1 WHERE ${quoteIdentifier(table.primaryKey)} = $2${scopeSuffix} RETURNING ${returningColumns}`,
|
|
2372
|
-
params: [deletedAt, id]
|
|
2373
|
-
};
|
|
2374
|
-
}
|
|
2375
|
-
function buildRestoreByIdQuery(table, id) {
|
|
2376
|
-
const deletedAtColumn = resolveSoftDeleteColumn(table);
|
|
2377
|
-
if (!deletedAtColumn) {
|
|
2378
|
-
throw new Error(`Table ${table.name} does not support soft deletes.`);
|
|
2379
|
-
}
|
|
2380
|
-
const returningColumns = buildReturningColumns(table);
|
|
2381
|
-
return {
|
|
2382
|
-
text: `UPDATE ${quoteIdentifier(table.name)} SET ${quoteIdentifier(deletedAtColumn)} = $1 WHERE ${quoteIdentifier(table.primaryKey)} = $2 AND ${qualifyColumn(table.name, deletedAtColumn)} IS NOT NULL RETURNING ${returningColumns}`,
|
|
2383
|
-
params: [null, id]
|
|
2384
|
-
};
|
|
2385
|
-
}
|
|
2386
|
-
function buildDeleteByIdQuery(table, id) {
|
|
2387
|
-
return {
|
|
2388
|
-
text: `DELETE FROM ${quoteIdentifier(table.name)} WHERE ${quoteIdentifier(table.primaryKey)} = $1 RETURNING ${quoteIdentifier(table.primaryKey)} AS ${quoteIdentifier("deleted_id")}`,
|
|
2389
|
-
params: [id]
|
|
2390
|
-
};
|
|
2391
|
-
}
|
|
2392
|
-
|
|
2393
|
-
// ../../src/core/database/relationships.ts
|
|
2394
|
-
function indexHasManyRelation(parents, children, relation) {
|
|
2395
|
-
const groups = new Map;
|
|
2396
|
-
for (const parent of parents) {
|
|
2397
|
-
groups.set(parent[relation.localKey], []);
|
|
2398
|
-
}
|
|
2399
|
-
for (const child of children) {
|
|
2400
|
-
const key = child[relation.foreignKey];
|
|
2401
|
-
const group = groups.get(key);
|
|
2402
|
-
if (!group) {
|
|
2403
|
-
continue;
|
|
2404
|
-
}
|
|
2405
|
-
group.push(child);
|
|
2406
|
-
}
|
|
2407
|
-
return groups;
|
|
2408
|
-
}
|
|
2409
|
-
function indexBelongsToRelation(children, parents, relation) {
|
|
2410
|
-
const parentsById = new Map;
|
|
2411
|
-
for (const parent of parents) {
|
|
2412
|
-
parentsById.set(parent[relation.ownerKey], parent);
|
|
2413
|
-
}
|
|
2414
|
-
const result = new Map;
|
|
2415
|
-
for (const child of children) {
|
|
2416
|
-
const foreignKey = child[relation.foreignKey];
|
|
2417
|
-
const parent = parentsById.get(foreignKey);
|
|
2418
|
-
if (parent) {
|
|
2419
|
-
result.set(foreignKey, parent);
|
|
2420
|
-
}
|
|
2421
|
-
}
|
|
2422
|
-
return result;
|
|
2423
|
-
}
|
|
2424
|
-
function indexMorphManyRelation(parents, children, relation) {
|
|
2425
|
-
const groups = new Map;
|
|
2426
|
-
for (const parent of parents) {
|
|
2427
|
-
groups.set(parent[relation.localKey], []);
|
|
2428
|
-
}
|
|
2429
|
-
for (const child of children) {
|
|
2430
|
-
if (child[relation.morphTypeKey] !== relation.morphType) {
|
|
2431
|
-
continue;
|
|
2432
|
-
}
|
|
2433
|
-
const key = child[relation.morphIdKey];
|
|
2434
|
-
const group = groups.get(key);
|
|
2435
|
-
if (!group) {
|
|
2436
|
-
continue;
|
|
2437
|
-
}
|
|
2438
|
-
group.push(child);
|
|
2439
|
-
}
|
|
2440
|
-
return groups;
|
|
2441
|
-
}
|
|
2442
|
-
function indexMorphToRelation(children, parentsByType, relation) {
|
|
2443
|
-
const result = new Map;
|
|
2444
|
-
for (const child of children) {
|
|
2445
|
-
const morphType = String(child[relation.morphTypeKey]);
|
|
2446
|
-
const parents = parentsByType.get(morphType);
|
|
2447
|
-
if (!parents) {
|
|
2448
|
-
continue;
|
|
2449
|
-
}
|
|
2450
|
-
const parent = parents.get(child[relation.morphIdKey]);
|
|
2451
|
-
if (parent) {
|
|
2452
|
-
result.set(child[relation.morphIdKey], parent);
|
|
2453
|
-
}
|
|
2454
|
-
}
|
|
2455
|
-
return result;
|
|
2456
|
-
}
|
|
2457
|
-
|
|
2458
|
-
// ../../src/core/database/boundConnection.ts
|
|
2459
|
-
var boundConnectionHolder = {
|
|
2460
|
-
connection: null
|
|
2461
|
-
};
|
|
2462
|
-
function getBoundDatabaseConnection() {
|
|
2463
|
-
return boundConnectionHolder.connection;
|
|
2464
|
-
}
|
|
2465
|
-
|
|
2466
|
-
// ../../src/core/database/repositoryConnection.ts
|
|
2467
|
-
function resolveRepositoryConnection() {
|
|
2468
|
-
return getBoundDatabaseConnection() ?? getDefaultDatabaseQuery();
|
|
2469
|
-
}
|
|
2470
|
-
var repositoryConnection = new Proxy(function repositoryConnection2() {}, {
|
|
2471
|
-
apply(_target, _thisArg, args) {
|
|
2472
|
-
return resolveRepositoryConnection()(...args);
|
|
2473
|
-
},
|
|
2474
|
-
get(_target, property) {
|
|
2475
|
-
const connection = resolveRepositoryConnection();
|
|
2476
|
-
const value = connection[property];
|
|
2477
|
-
return typeof value === "function" ? value.bind(connection) : value;
|
|
2478
|
-
}
|
|
2479
|
-
});
|
|
2480
|
-
|
|
2481
|
-
// ../../src/core/database/whereBuilder.ts
|
|
2482
|
-
class WhereBuilder {
|
|
2483
|
-
nodes = [];
|
|
2484
|
-
where(where) {
|
|
2485
|
-
this.nodes.push({ kind: "and", where });
|
|
2486
|
-
return this;
|
|
2487
|
-
}
|
|
2488
|
-
orWhere(where) {
|
|
2489
|
-
this.nodes.push({ kind: "or", where });
|
|
2490
|
-
return this;
|
|
2491
|
-
}
|
|
2492
|
-
whereGroup(fn) {
|
|
2493
|
-
const nested = new WhereBuilder;
|
|
2494
|
-
fn(nested);
|
|
2495
|
-
if (nested.nodes.length > 0) {
|
|
2496
|
-
this.nodes.push({ kind: "and", group: nested.nodes });
|
|
2497
|
-
}
|
|
2498
|
-
return this;
|
|
2499
|
-
}
|
|
2500
|
-
orWhereGroup(fn) {
|
|
2501
|
-
const nested = new WhereBuilder;
|
|
2502
|
-
fn(nested);
|
|
2503
|
-
if (nested.nodes.length > 0) {
|
|
2504
|
-
this.nodes.push({ kind: "or", group: nested.nodes });
|
|
2505
|
-
}
|
|
2506
|
-
return this;
|
|
2507
|
-
}
|
|
2508
|
-
}
|
|
2509
|
-
|
|
2510
|
-
// ../../src/core/database/repositoryQuery.ts
|
|
2511
|
-
class RepositoryQuery {
|
|
2512
|
-
repository;
|
|
2513
|
-
whereClause;
|
|
2514
|
-
queryOptions;
|
|
2515
|
-
eagerLoads = [];
|
|
2516
|
-
whereNodes = [];
|
|
2517
|
-
constructor(repository, whereClause = {}, queryOptions = {}) {
|
|
2518
|
-
this.repository = repository;
|
|
2519
|
-
this.whereClause = whereClause;
|
|
2520
|
-
this.queryOptions = queryOptions;
|
|
2521
|
-
}
|
|
2522
|
-
where(input) {
|
|
2523
|
-
if (typeof input === "function") {
|
|
2524
|
-
const builder = new WhereBuilder;
|
|
2525
|
-
input(builder);
|
|
2526
|
-
this.whereNodes.push(...builder.nodes);
|
|
2527
|
-
return this;
|
|
2528
|
-
}
|
|
2529
|
-
this.whereClause = { ...this.whereClause, ...input };
|
|
2530
|
-
return this;
|
|
2531
|
-
}
|
|
2532
|
-
orWhere(input) {
|
|
2533
|
-
if (typeof input === "function") {
|
|
2534
|
-
const builder = new WhereBuilder;
|
|
2535
|
-
input(builder);
|
|
2536
|
-
if (builder.nodes.length > 0) {
|
|
2537
|
-
this.whereNodes.push({ kind: "or", group: builder.nodes });
|
|
2538
|
-
}
|
|
2539
|
-
return this;
|
|
2540
|
-
}
|
|
2541
|
-
this.whereNodes.push({ kind: "or", where: input });
|
|
2542
|
-
return this;
|
|
2543
|
-
}
|
|
2544
|
-
orderBy(orderBy) {
|
|
2545
|
-
this.queryOptions = { ...this.queryOptions, orderBy };
|
|
2546
|
-
return this;
|
|
2547
|
-
}
|
|
2548
|
-
limit(limit) {
|
|
2549
|
-
this.queryOptions = { ...this.queryOptions, limit };
|
|
2550
|
-
return this;
|
|
2551
|
-
}
|
|
2552
|
-
offset(offset) {
|
|
2553
|
-
this.queryOptions = { ...this.queryOptions, offset };
|
|
2554
|
-
return this;
|
|
2555
|
-
}
|
|
2556
|
-
join(left, right) {
|
|
2557
|
-
return this.addJoin("inner", left, right);
|
|
2558
|
-
}
|
|
2559
|
-
leftJoin(left, right) {
|
|
2560
|
-
return this.addJoin("left", left, right);
|
|
2561
|
-
}
|
|
2562
|
-
groupBy(groupBy) {
|
|
2563
|
-
this.queryOptions = { ...this.queryOptions, groupBy };
|
|
2564
|
-
return this;
|
|
2565
|
-
}
|
|
2566
|
-
having(having) {
|
|
2567
|
-
this.queryOptions = { ...this.queryOptions, having };
|
|
2568
|
-
return this;
|
|
2569
|
-
}
|
|
2570
|
-
withHasMany(as, relation, childRepository, options = {}) {
|
|
2571
|
-
this.eagerLoads.push({
|
|
2572
|
-
kind: "hasMany",
|
|
2573
|
-
as,
|
|
2574
|
-
relation,
|
|
2575
|
-
repository: childRepository,
|
|
2576
|
-
options
|
|
2577
|
-
});
|
|
2578
|
-
return this;
|
|
2579
|
-
}
|
|
2580
|
-
withBelongsTo(as, relation, parentRepository, options = {}) {
|
|
2581
|
-
this.eagerLoads.push({
|
|
2582
|
-
kind: "belongsTo",
|
|
2583
|
-
as,
|
|
2584
|
-
relation,
|
|
2585
|
-
repository: parentRepository,
|
|
2586
|
-
options
|
|
2587
|
-
});
|
|
2588
|
-
return this;
|
|
2589
|
-
}
|
|
2590
|
-
withMorphMany(as, relation, childRepository, options = {}) {
|
|
2591
|
-
this.eagerLoads.push({
|
|
2592
|
-
kind: "morphMany",
|
|
2593
|
-
as,
|
|
2594
|
-
relation,
|
|
2595
|
-
repository: childRepository,
|
|
2596
|
-
options
|
|
2597
|
-
});
|
|
2598
|
-
return this;
|
|
2599
|
-
}
|
|
2600
|
-
withMorphOne(as, relation, childRepository, options = {}) {
|
|
2601
|
-
this.eagerLoads.push({
|
|
2602
|
-
kind: "morphOne",
|
|
2603
|
-
as,
|
|
2604
|
-
relation,
|
|
2605
|
-
repository: childRepository,
|
|
2606
|
-
options
|
|
2607
|
-
});
|
|
2608
|
-
return this;
|
|
2609
|
-
}
|
|
2610
|
-
withMorphTo(as, relation, repositoriesByType, options = {}) {
|
|
2611
|
-
this.eagerLoads.push({
|
|
2612
|
-
kind: "morphTo",
|
|
2613
|
-
as,
|
|
2614
|
-
relation,
|
|
2615
|
-
repository: this.repository,
|
|
2616
|
-
morphRepositories: repositoriesByType,
|
|
2617
|
-
options
|
|
2618
|
-
});
|
|
2619
|
-
return this;
|
|
2620
|
-
}
|
|
2621
|
-
async get() {
|
|
2622
|
-
const rows = await this.repository.findAll(this.buildOptions());
|
|
2623
|
-
return await this.attach(rows);
|
|
2624
|
-
}
|
|
2625
|
-
async first() {
|
|
2626
|
-
const rows = await this.get();
|
|
2627
|
-
return rows[0] ?? null;
|
|
2628
|
-
}
|
|
2629
|
-
async paginate(options) {
|
|
2630
|
-
return await this.repository.paginate({
|
|
2631
|
-
...this.buildOptions(),
|
|
2632
|
-
page: options.page,
|
|
2633
|
-
perPage: options.perPage
|
|
2634
|
-
});
|
|
2635
|
-
}
|
|
2636
|
-
buildOptions() {
|
|
2637
|
-
return {
|
|
2638
|
-
...this.queryOptions,
|
|
2639
|
-
where: this.whereClause,
|
|
2640
|
-
whereNodes: this.whereNodes
|
|
2641
|
-
};
|
|
2642
|
-
}
|
|
2643
|
-
addJoin(type, left, right) {
|
|
2644
|
-
const leftRef = parseQualifiedColumn(left);
|
|
2645
|
-
const rightRef = parseQualifiedColumn(right);
|
|
2646
|
-
const table = type === "inner" ? rightRef.table : rightRef.table;
|
|
2647
|
-
const joins = this.queryOptions.joins ?? [];
|
|
2648
|
-
const existing = joins.find((join3) => join3.table === table && join3.type === type);
|
|
2649
|
-
if (existing) {
|
|
2650
|
-
existing.on.push({ left: leftRef, right: rightRef });
|
|
2651
|
-
return this;
|
|
2652
|
-
}
|
|
2653
|
-
this.queryOptions = {
|
|
2654
|
-
...this.queryOptions,
|
|
2655
|
-
joins: [
|
|
2656
|
-
...joins,
|
|
2657
|
-
{
|
|
2658
|
-
type,
|
|
2659
|
-
table,
|
|
2660
|
-
on: [{ left: leftRef, right: rightRef }]
|
|
2661
|
-
}
|
|
2662
|
-
]
|
|
2663
|
-
};
|
|
2664
|
-
return this;
|
|
2665
|
-
}
|
|
2666
|
-
async attach(rows) {
|
|
2667
|
-
if (rows.length === 0 || this.eagerLoads.length === 0) {
|
|
2668
|
-
return rows.map((row) => ({ ...row }));
|
|
2669
|
-
}
|
|
2670
|
-
let result = rows.map((row) => ({ ...row }));
|
|
2671
|
-
for (const load of this.eagerLoads) {
|
|
2672
|
-
if (load.kind === "hasMany") {
|
|
2673
|
-
const relation2 = load.relation;
|
|
2674
|
-
const grouped2 = await load.repository.withConnection(this.repository.getConnection()).loadHasManyForParents(rows, relation2, load.options);
|
|
2675
|
-
result = result.map((row) => ({
|
|
2676
|
-
...row,
|
|
2677
|
-
[load.as]: grouped2.get(row[relation2.localKey]) ?? []
|
|
2678
|
-
}));
|
|
2679
|
-
continue;
|
|
2680
|
-
}
|
|
2681
|
-
if (load.kind === "morphMany") {
|
|
2682
|
-
const relation2 = load.relation;
|
|
2683
|
-
const grouped2 = await load.repository.withConnection(this.repository.getConnection()).loadMorphManyForParents(rows, relation2, load.options);
|
|
2684
|
-
result = result.map((row) => ({
|
|
2685
|
-
...row,
|
|
2686
|
-
[load.as]: grouped2.get(row[relation2.localKey]) ?? []
|
|
2687
|
-
}));
|
|
2688
|
-
continue;
|
|
2689
|
-
}
|
|
2690
|
-
if (load.kind === "morphOne") {
|
|
2691
|
-
const relation2 = load.relation;
|
|
2692
|
-
const grouped2 = await load.repository.withConnection(this.repository.getConnection()).loadMorphOneForParents(rows, relation2, load.options);
|
|
2693
|
-
result = result.map((row) => ({
|
|
2694
|
-
...row,
|
|
2695
|
-
[load.as]: grouped2.get(row[relation2.localKey])
|
|
2696
|
-
}));
|
|
2697
|
-
continue;
|
|
2698
|
-
}
|
|
2699
|
-
if (load.kind === "morphTo") {
|
|
2700
|
-
const relation2 = load.relation;
|
|
2701
|
-
const grouped2 = await this.repository.loadMorphToForChildren(rows, relation2, load.morphRepositories ?? new Map, load.options);
|
|
2702
|
-
result = result.map((row) => ({
|
|
2703
|
-
...row,
|
|
2704
|
-
[load.as]: grouped2.get(row[relation2.morphIdKey])
|
|
2705
|
-
}));
|
|
2706
|
-
continue;
|
|
2707
|
-
}
|
|
2708
|
-
const relation = load.relation;
|
|
2709
|
-
const grouped = await this.repository.loadBelongsToForParents(rows, relation, load.repository, load.options);
|
|
2710
|
-
result = result.map((row) => ({
|
|
2711
|
-
...row,
|
|
2712
|
-
[load.as]: grouped.get(row[relation.foreignKey])
|
|
2713
|
-
}));
|
|
2714
|
-
}
|
|
2715
|
-
return result;
|
|
2716
|
-
}
|
|
2717
|
-
}
|
|
2718
|
-
|
|
2719
|
-
// ../../src/core/database/baseRepository.ts
|
|
2720
|
-
class BaseRepository5 {
|
|
2721
|
-
table;
|
|
2722
|
-
connection;
|
|
2723
|
-
constructor(table, connection = repositoryConnection) {
|
|
2724
|
-
this.table = table;
|
|
2725
|
-
this.connection = connection;
|
|
2726
|
-
}
|
|
2727
|
-
async findAll(options = {}) {
|
|
2728
|
-
return await withDatabaseErrorHandling(async () => {
|
|
2729
|
-
const { whereNodes, ...queryOptions } = options;
|
|
2730
|
-
const { text, params } = buildSelectQuery(this.table, queryOptions, whereNodes ?? []);
|
|
2731
|
-
return await this.connection.unsafe(text, params);
|
|
2732
|
-
});
|
|
2733
|
-
}
|
|
2734
|
-
async paginate(options) {
|
|
2735
|
-
const { whereNodes, where = {}, page, perPage, ...queryOptions } = options;
|
|
2736
|
-
const total = await this.countWhere(where, {
|
|
2737
|
-
withTrashed: options.withTrashed,
|
|
2738
|
-
onlyTrashed: options.onlyTrashed,
|
|
2739
|
-
joins: options.joins,
|
|
2740
|
-
groupBy: options.groupBy
|
|
2741
|
-
}, whereNodes);
|
|
2742
|
-
const offset = (page - 1) * perPage;
|
|
2743
|
-
const data = await this.findAll({
|
|
2744
|
-
...queryOptions,
|
|
2745
|
-
where,
|
|
2746
|
-
whereNodes,
|
|
2747
|
-
limit: perPage,
|
|
2748
|
-
offset
|
|
2749
|
-
});
|
|
2750
|
-
return {
|
|
2751
|
-
data,
|
|
2752
|
-
meta: buildPaginationMeta({ page, perPage, total })
|
|
2753
|
-
};
|
|
2754
|
-
}
|
|
2755
|
-
async chunk(count, callback, options = {}) {
|
|
2756
|
-
if (!Number.isInteger(count) || count <= 0) {
|
|
2757
|
-
throw new Error("Chunk size must be a positive integer.");
|
|
2758
|
-
}
|
|
2759
|
-
let offset = 0;
|
|
2760
|
-
while (true) {
|
|
2761
|
-
const rows = await this.findAll({
|
|
2762
|
-
...options,
|
|
2763
|
-
limit: count,
|
|
2764
|
-
offset
|
|
2765
|
-
});
|
|
2766
|
-
if (rows.length === 0) {
|
|
2767
|
-
return;
|
|
2768
|
-
}
|
|
2769
|
-
const shouldContinue = await callback(rows);
|
|
2770
|
-
if (shouldContinue === false || rows.length < count) {
|
|
2771
|
-
return;
|
|
2772
|
-
}
|
|
2773
|
-
offset += count;
|
|
2774
|
-
}
|
|
2775
|
-
}
|
|
2776
|
-
async cursorPaginate(options) {
|
|
2777
|
-
const {
|
|
2778
|
-
perPage,
|
|
2779
|
-
cursor,
|
|
2780
|
-
cursorColumn = this.table.primaryKey,
|
|
2781
|
-
direction = "asc",
|
|
2782
|
-
where = {},
|
|
2783
|
-
whereNodes,
|
|
2784
|
-
...queryOptions
|
|
2785
|
-
} = options;
|
|
2786
|
-
if (!Number.isInteger(perPage) || perPage <= 0) {
|
|
2787
|
-
throw new Error("Cursor page size must be a positive integer.");
|
|
2788
|
-
}
|
|
2789
|
-
const cursorWhere = { ...where };
|
|
2790
|
-
if (cursor !== undefined) {
|
|
2791
|
-
cursorWhere[cursorColumn] = direction === "asc" ? { gt: cursor } : { lt: cursor };
|
|
2792
|
-
}
|
|
2793
|
-
const rows = await this.findAll({
|
|
2794
|
-
...queryOptions,
|
|
2795
|
-
where: cursorWhere,
|
|
2796
|
-
whereNodes,
|
|
2797
|
-
orderBy: { [cursorColumn]: direction },
|
|
2798
|
-
limit: perPage + 1
|
|
2799
|
-
});
|
|
2800
|
-
const hasMore = rows.length > perPage;
|
|
2801
|
-
const data = hasMore ? rows.slice(0, perPage) : rows;
|
|
2802
|
-
const nextCursor = hasMore ? data[data.length - 1]?.[cursorColumn] ?? null : null;
|
|
2803
|
-
const prevCursor = cursor ?? null;
|
|
2804
|
-
return {
|
|
2805
|
-
data,
|
|
2806
|
-
meta: {
|
|
2807
|
-
per_page: perPage,
|
|
2808
|
-
next_cursor: nextCursor,
|
|
2809
|
-
prev_cursor: prevCursor,
|
|
2810
|
-
has_more: hasMore
|
|
2811
|
-
}
|
|
2812
|
-
};
|
|
2813
|
-
}
|
|
2814
|
-
async findById(id) {
|
|
2815
|
-
return await this.firstOrNull({
|
|
2816
|
-
[this.table.primaryKey]: id
|
|
2817
|
-
});
|
|
2818
|
-
}
|
|
2819
|
-
async findByIdOrThrow(id, errorFactory) {
|
|
2820
|
-
const record = await this.findById(id);
|
|
2821
|
-
if (record) {
|
|
2822
|
-
return record;
|
|
2823
|
-
}
|
|
2824
|
-
throw errorFactory?.(id) ?? new Error(`${this.table.name} ${String(id)} was not found.`);
|
|
2825
|
-
}
|
|
2826
|
-
async findByIds(ids) {
|
|
2827
|
-
const uniqueIds = [...new Set(ids)];
|
|
2828
|
-
if (uniqueIds.length === 0) {
|
|
2829
|
-
return [];
|
|
2830
|
-
}
|
|
2831
|
-
return await this.findWhere({
|
|
2832
|
-
[this.table.primaryKey]: uniqueIds
|
|
2833
|
-
});
|
|
2834
|
-
}
|
|
2835
|
-
async firstOrNull(where, options = {}) {
|
|
2836
|
-
const [record] = await this.findAll({ ...options, where, limit: 1 });
|
|
2837
|
-
return record ?? null;
|
|
2838
|
-
}
|
|
2839
|
-
async create(values) {
|
|
2840
|
-
return await withDatabaseErrorHandling(async () => {
|
|
2841
|
-
const { text, params } = buildInsertQuery(this.table, values);
|
|
2842
|
-
const [record] = await this.connection.unsafe(text, params);
|
|
2843
|
-
if (!record) {
|
|
2844
|
-
throw new Error(`Insert into ${this.table.name} did not return a record.`);
|
|
2845
|
-
}
|
|
2846
|
-
const entity = record;
|
|
2847
|
-
await eventBus.dispatch(modelEventName(this.table.name, "created"), entity);
|
|
2848
|
-
return entity;
|
|
2849
|
-
});
|
|
2850
|
-
}
|
|
2851
|
-
async updateById(id, changes) {
|
|
2852
|
-
return await withDatabaseErrorHandling(async () => {
|
|
2853
|
-
const { text, params } = buildUpdateQuery(this.table, id, changes);
|
|
2854
|
-
const [record] = await this.connection.unsafe(text, params);
|
|
2855
|
-
const entity = record ?? null;
|
|
2856
|
-
if (entity) {
|
|
2857
|
-
await eventBus.dispatch(modelEventName(this.table.name, "updated"), entity);
|
|
2858
|
-
}
|
|
2859
|
-
return entity;
|
|
2860
|
-
});
|
|
2861
|
-
}
|
|
2862
|
-
async updateByIdOrThrow(id, changes, errorFactory) {
|
|
2863
|
-
const record = await this.updateById(id, changes);
|
|
2864
|
-
if (record) {
|
|
2865
|
-
return record;
|
|
2866
|
-
}
|
|
2867
|
-
throw errorFactory?.(id) ?? new Error(`${this.table.name} ${String(id)} was not found.`);
|
|
2868
|
-
}
|
|
2869
|
-
async deleteById(id) {
|
|
2870
|
-
if (resolveSoftDeleteColumn(this.table)) {
|
|
2871
|
-
return await this.softDeleteById(id);
|
|
2872
|
-
}
|
|
2873
|
-
return await this.forceDeleteById(id);
|
|
2874
|
-
}
|
|
2875
|
-
async softDeleteById(id) {
|
|
2876
|
-
return await withDatabaseErrorHandling(async () => {
|
|
2877
|
-
const { text, params } = buildSoftDeleteByIdQuery(this.table, id, new Date);
|
|
2878
|
-
const [record] = await this.connection.unsafe(text, params);
|
|
2879
|
-
if (!record) {
|
|
2880
|
-
return false;
|
|
2881
|
-
}
|
|
2882
|
-
await eventBus.dispatch(modelEventName(this.table.name, "deleted"), record);
|
|
2883
|
-
return true;
|
|
2884
|
-
});
|
|
2885
|
-
}
|
|
2886
|
-
async forceDeleteById(id) {
|
|
2887
|
-
return await withDatabaseErrorHandling(async () => {
|
|
2888
|
-
const { text, params } = buildDeleteByIdQuery(this.table, id);
|
|
2889
|
-
const [row] = await this.connection.unsafe(text, params);
|
|
2890
|
-
if (!row) {
|
|
2891
|
-
return false;
|
|
2892
|
-
}
|
|
2893
|
-
await eventBus.dispatch(modelEventName(this.table.name, "force-deleted"), {
|
|
2894
|
-
id
|
|
2895
|
-
});
|
|
2896
|
-
return true;
|
|
2897
|
-
});
|
|
2898
|
-
}
|
|
2899
|
-
async restoreById(id) {
|
|
2900
|
-
return await withDatabaseErrorHandling(async () => {
|
|
2901
|
-
const { text, params } = buildRestoreByIdQuery(this.table, id);
|
|
2902
|
-
const [record] = await this.connection.unsafe(text, params);
|
|
2903
|
-
if (!record) {
|
|
2904
|
-
return null;
|
|
2905
|
-
}
|
|
2906
|
-
const entity = record;
|
|
2907
|
-
await eventBus.dispatch(modelEventName(this.table.name, "restored"), entity);
|
|
2908
|
-
return entity;
|
|
2909
|
-
});
|
|
2910
|
-
}
|
|
2911
|
-
withConnection(connection) {
|
|
2912
|
-
const clone = Object.create(Object.getPrototypeOf(this));
|
|
2913
|
-
Object.assign(clone, this);
|
|
2914
|
-
clone.connection = connection;
|
|
2915
|
-
return clone;
|
|
2916
|
-
}
|
|
2917
|
-
getConnection() {
|
|
2918
|
-
return this.connection;
|
|
2919
|
-
}
|
|
2920
|
-
getTable() {
|
|
2921
|
-
return this.table;
|
|
2922
|
-
}
|
|
2923
|
-
query(where = {}) {
|
|
2924
|
-
return new RepositoryQuery(this, where);
|
|
2925
|
-
}
|
|
2926
|
-
async findWhere(where, options = {}) {
|
|
2927
|
-
return await this.findAll({ ...options, where });
|
|
2928
|
-
}
|
|
2929
|
-
async countWhere(where = {}, options = {}, whereNodes = []) {
|
|
2930
|
-
const { text, params } = buildCountQuery(this.table, where, options, whereNodes);
|
|
2931
|
-
const [row] = await this.connection.unsafe(text, params);
|
|
2932
|
-
return Number(row?.count ?? 0);
|
|
2933
|
-
}
|
|
2934
|
-
async averageColumn(column, where = {}) {
|
|
2935
|
-
const qualifiedColumn = qualifyColumn(this.table.name, column);
|
|
2936
|
-
return await this.averageExpression(`AVG(${qualifiedColumn})`, "value", where);
|
|
2937
|
-
}
|
|
2938
|
-
async averageExpression(expression, alias, where = {}) {
|
|
2939
|
-
const { text, params } = buildProjectionQuery(this.table, expression, alias, { where });
|
|
2940
|
-
const [row] = await this.connection.unsafe(text, params);
|
|
2941
|
-
return Math.round(Number(row?.[alias] ?? 0));
|
|
2942
|
-
}
|
|
2943
|
-
async pluckNumberValues(expression, alias, options = {}) {
|
|
2944
|
-
const { text, params } = buildProjectionQuery(this.table, expression, alias, options);
|
|
2945
|
-
const rows = await this.connection.unsafe(text, params);
|
|
2946
|
-
return rows.flatMap((row) => {
|
|
2947
|
-
const value = row[alias];
|
|
2948
|
-
return value === null || value === undefined ? [] : [Number(value)];
|
|
2949
|
-
});
|
|
2950
|
-
}
|
|
2951
|
-
async countGroupedBy(column, where = {}) {
|
|
2952
|
-
const { text, params } = buildGroupedCountQuery(this.table, column, where);
|
|
2953
|
-
const rows = await this.connection.unsafe(text, params);
|
|
2954
|
-
return rows.map(({ value, count }) => ({
|
|
2955
|
-
value,
|
|
2956
|
-
count: Number(count)
|
|
2957
|
-
}));
|
|
2958
|
-
}
|
|
2959
|
-
async findByHasManyRelation(relation, parentId, options = {}) {
|
|
2960
|
-
return await this.findWhere({
|
|
2961
|
-
[relation.foreignKey]: parentId
|
|
2962
|
-
}, options);
|
|
2963
|
-
}
|
|
2964
|
-
async loadHasManyForParents(parents, relation, options = {}) {
|
|
2965
|
-
if (parents.length === 0) {
|
|
2966
|
-
return indexHasManyRelation(parents, [], relation);
|
|
2967
|
-
}
|
|
2968
|
-
const parentIds = [...new Set(parents.map((parent) => parent[relation.localKey]))];
|
|
2969
|
-
const children = await this.findWhere({
|
|
2970
|
-
[relation.foreignKey]: parentIds
|
|
2971
|
-
}, options);
|
|
2972
|
-
return indexHasManyRelation(parents, children, relation);
|
|
2973
|
-
}
|
|
2974
|
-
async loadBelongsToForParents(children, relation, parentRepository, options = {}) {
|
|
2975
|
-
if (children.length === 0) {
|
|
2976
|
-
return new Map;
|
|
2977
|
-
}
|
|
2978
|
-
const ownerIds = [...new Set(children.map((child) => child[relation.foreignKey]))];
|
|
2979
|
-
const parents = await parentRepository.withConnection(this.connection).findWhere({
|
|
2980
|
-
[relation.ownerKey]: ownerIds
|
|
2981
|
-
}, options);
|
|
2982
|
-
return indexBelongsToRelation(children, parents, relation);
|
|
2983
|
-
}
|
|
2984
|
-
async loadMorphManyForParents(parents, relation, options = {}) {
|
|
2985
|
-
if (parents.length === 0) {
|
|
2986
|
-
return indexMorphManyRelation(parents, [], relation);
|
|
2987
|
-
}
|
|
2988
|
-
const parentIds = [...new Set(parents.map((parent) => parent[relation.localKey]))];
|
|
2989
|
-
const children = await this.findWhere({
|
|
2990
|
-
[relation.morphTypeKey]: relation.morphType,
|
|
2991
|
-
[relation.morphIdKey]: parentIds
|
|
2992
|
-
}, options);
|
|
2993
|
-
return indexMorphManyRelation(parents, children, relation);
|
|
2994
|
-
}
|
|
2995
|
-
async loadMorphOneForParents(parents, relation, options = {}) {
|
|
2996
|
-
const grouped = await this.loadMorphManyForParents(parents, relation, options);
|
|
2997
|
-
const result = new Map;
|
|
2998
|
-
for (const parent of parents) {
|
|
2999
|
-
const matches = grouped.get(parent[relation.localKey]) ?? [];
|
|
3000
|
-
result.set(parent[relation.localKey], matches[0]);
|
|
3001
|
-
}
|
|
3002
|
-
return result;
|
|
3003
|
-
}
|
|
3004
|
-
async loadMorphToForChildren(children, relation, repositoriesByType, options = {}) {
|
|
3005
|
-
if (children.length === 0) {
|
|
3006
|
-
return new Map;
|
|
3007
|
-
}
|
|
3008
|
-
const idsByType = new Map;
|
|
3009
|
-
for (const child of children) {
|
|
3010
|
-
const morphType = String(child[relation.morphTypeKey]);
|
|
3011
|
-
const morphId = child[relation.morphIdKey];
|
|
3012
|
-
const ids = idsByType.get(morphType) ?? new Set;
|
|
3013
|
-
ids.add(morphId);
|
|
3014
|
-
idsByType.set(morphType, ids);
|
|
3015
|
-
}
|
|
3016
|
-
const parentsByType = new Map;
|
|
3017
|
-
for (const [morphType, ids] of idsByType) {
|
|
3018
|
-
const repository = repositoriesByType.get(morphType);
|
|
3019
|
-
if (!repository) {
|
|
3020
|
-
continue;
|
|
3021
|
-
}
|
|
3022
|
-
const ownerKey = repository.getTable().primaryKey;
|
|
3023
|
-
const parents = await repository.withConnection(this.connection).findWhere({
|
|
3024
|
-
[ownerKey]: [...ids]
|
|
3025
|
-
}, options);
|
|
3026
|
-
const indexed = new Map;
|
|
3027
|
-
for (const parent of parents) {
|
|
3028
|
-
indexed.set(parent[ownerKey], parent);
|
|
3029
|
-
}
|
|
3030
|
-
parentsByType.set(morphType, indexed);
|
|
3031
|
-
}
|
|
3032
|
-
return indexMorphToRelation(children, parentsByType, relation);
|
|
3033
|
-
}
|
|
3034
|
-
}
|
|
3035
|
-
var baseRepository_default = BaseRepository5;
|
|
3036
|
-
// ../../src/core/database/model.ts
|
|
3037
|
-
var modelRepositories = new WeakMap;
|
|
3038
|
-
var modelGlobalScopes = new WeakMap;
|
|
3039
|
-
var modelBooted = new WeakSet;
|
|
3040
|
-
// ../../src/core/database/schema/columnDefinition.ts
|
|
3041
|
-
class ColumnDefinition {
|
|
3042
|
-
name;
|
|
3043
|
-
kind;
|
|
3044
|
-
length;
|
|
3045
|
-
isNullable = false;
|
|
3046
|
-
isPrimary = false;
|
|
3047
|
-
isUnique = false;
|
|
3048
|
-
autoIncrement = false;
|
|
3049
|
-
defaultValue;
|
|
3050
|
-
checkExpression;
|
|
3051
|
-
foreignKey;
|
|
3052
|
-
constructor(name, kind) {
|
|
3053
|
-
this.name = name;
|
|
3054
|
-
this.kind = kind;
|
|
3055
|
-
}
|
|
3056
|
-
nullable() {
|
|
3057
|
-
this.isNullable = true;
|
|
3058
|
-
return this;
|
|
3059
|
-
}
|
|
3060
|
-
notNullable() {
|
|
3061
|
-
this.isNullable = false;
|
|
3062
|
-
return this;
|
|
3063
|
-
}
|
|
3064
|
-
default(value) {
|
|
3065
|
-
if (typeof value === "boolean") {
|
|
3066
|
-
this.defaultValue = value ? "TRUE" : "FALSE";
|
|
3067
|
-
return this;
|
|
3068
|
-
}
|
|
3069
|
-
if (typeof value === "number") {
|
|
3070
|
-
this.defaultValue = String(value);
|
|
3071
|
-
return this;
|
|
3072
|
-
}
|
|
3073
|
-
this.defaultValue = `'${value.replace(/'/g, "''")}'`;
|
|
3074
|
-
return this;
|
|
3075
|
-
}
|
|
3076
|
-
defaultRaw(expression) {
|
|
3077
|
-
this.defaultValue = expression;
|
|
3078
|
-
return this;
|
|
3079
|
-
}
|
|
3080
|
-
unique() {
|
|
3081
|
-
this.isUnique = true;
|
|
3082
|
-
return this;
|
|
3083
|
-
}
|
|
3084
|
-
primary() {
|
|
3085
|
-
this.isPrimary = true;
|
|
3086
|
-
return this;
|
|
3087
|
-
}
|
|
3088
|
-
check(expression) {
|
|
3089
|
-
this.checkExpression = expression;
|
|
3090
|
-
return this;
|
|
3091
|
-
}
|
|
3092
|
-
}
|
|
3093
|
-
|
|
3094
|
-
class ForeignIdColumnDefinition extends ColumnDefinition {
|
|
3095
|
-
constructor(name) {
|
|
3096
|
-
super(name, "foreignId");
|
|
3097
|
-
this.notNullable();
|
|
3098
|
-
}
|
|
3099
|
-
references(table, column = "id") {
|
|
3100
|
-
this.foreignKey = {
|
|
3101
|
-
referencesTable: table,
|
|
3102
|
-
referencesColumn: column
|
|
3103
|
-
};
|
|
3104
|
-
return this;
|
|
3105
|
-
}
|
|
3106
|
-
constrained(table) {
|
|
3107
|
-
const referencesTable = table ?? inferReferencedTable(this.name);
|
|
3108
|
-
return this.references(referencesTable);
|
|
3109
|
-
}
|
|
3110
|
-
cascadeOnDelete() {
|
|
3111
|
-
if (!this.foreignKey) {
|
|
3112
|
-
throw new Error(`Foreign key is not defined for column ${this.name}`);
|
|
3113
|
-
}
|
|
3114
|
-
this.foreignKey.onDelete = "cascade";
|
|
3115
|
-
return this;
|
|
3116
|
-
}
|
|
3117
|
-
nullOnDelete() {
|
|
3118
|
-
if (!this.foreignKey) {
|
|
3119
|
-
throw new Error(`Foreign key is not defined for column ${this.name}`);
|
|
3120
|
-
}
|
|
3121
|
-
this.foreignKey.onDelete = "set null";
|
|
3122
|
-
return this;
|
|
3123
|
-
}
|
|
3124
|
-
}
|
|
3125
|
-
function inferReferencedTable(columnName) {
|
|
3126
|
-
if (!columnName.endsWith("_id")) {
|
|
3127
|
-
throw new Error(`Cannot infer referenced table from column ${columnName}`);
|
|
3128
|
-
}
|
|
3129
|
-
return columnName.slice(0, -3);
|
|
3130
|
-
}
|
|
3131
|
-
|
|
3132
|
-
// ../../src/core/database/schema/blueprint.ts
|
|
3133
|
-
class Blueprint {
|
|
3134
|
-
table;
|
|
3135
|
-
action;
|
|
3136
|
-
columns = [];
|
|
3137
|
-
indexes = [];
|
|
3138
|
-
droppedColumns = [];
|
|
3139
|
-
droppedIndexes = [];
|
|
3140
|
-
constructor(table, action) {
|
|
3141
|
-
this.table = table;
|
|
3142
|
-
this.action = action;
|
|
3143
|
-
}
|
|
3144
|
-
id(name = "id") {
|
|
3145
|
-
const column = new ColumnDefinition(name, "id");
|
|
3146
|
-
column.primary();
|
|
3147
|
-
column.autoIncrement = true;
|
|
3148
|
-
this.columns.push(column);
|
|
3149
|
-
return column;
|
|
3150
|
-
}
|
|
3151
|
-
string(name, length) {
|
|
3152
|
-
const column = new ColumnDefinition(name, "string");
|
|
3153
|
-
column.length = length;
|
|
3154
|
-
column.notNullable();
|
|
3155
|
-
this.columns.push(column);
|
|
3156
|
-
return column;
|
|
3157
|
-
}
|
|
3158
|
-
text(name) {
|
|
3159
|
-
const column = new ColumnDefinition(name, "text");
|
|
3160
|
-
column.notNullable();
|
|
3161
|
-
this.columns.push(column);
|
|
3162
|
-
return column;
|
|
3163
|
-
}
|
|
3164
|
-
boolean(name) {
|
|
3165
|
-
const column = new ColumnDefinition(name, "boolean");
|
|
3166
|
-
column.notNullable();
|
|
3167
|
-
this.columns.push(column);
|
|
3168
|
-
return column;
|
|
3169
|
-
}
|
|
3170
|
-
integer(name) {
|
|
3171
|
-
const column = new ColumnDefinition(name, "integer");
|
|
3172
|
-
column.notNullable();
|
|
3173
|
-
this.columns.push(column);
|
|
3174
|
-
return column;
|
|
3175
|
-
}
|
|
3176
|
-
bigInteger(name) {
|
|
3177
|
-
const column = new ColumnDefinition(name, "bigInteger");
|
|
3178
|
-
column.notNullable();
|
|
3179
|
-
this.columns.push(column);
|
|
3180
|
-
return column;
|
|
3181
|
-
}
|
|
3182
|
-
timestamp(name) {
|
|
3183
|
-
const column = new ColumnDefinition(name, "timestamp");
|
|
3184
|
-
column.notNullable();
|
|
3185
|
-
this.columns.push(column);
|
|
3186
|
-
return column;
|
|
3187
|
-
}
|
|
3188
|
-
json(name) {
|
|
3189
|
-
const column = new ColumnDefinition(name, "json");
|
|
3190
|
-
column.notNullable();
|
|
3191
|
-
this.columns.push(column);
|
|
3192
|
-
return column;
|
|
3193
|
-
}
|
|
3194
|
-
jsonb(name) {
|
|
3195
|
-
const column = new ColumnDefinition(name, "jsonb");
|
|
3196
|
-
column.notNullable();
|
|
3197
|
-
this.columns.push(column);
|
|
3198
|
-
return column;
|
|
3199
|
-
}
|
|
3200
|
-
foreignId(name) {
|
|
3201
|
-
const column = new ForeignIdColumnDefinition(name);
|
|
3202
|
-
this.columns.push(column);
|
|
3203
|
-
return column;
|
|
3204
|
-
}
|
|
3205
|
-
timestamps() {
|
|
3206
|
-
this.timestamp("created_at").defaultRaw("NOW()");
|
|
3207
|
-
this.timestamp("updated_at").defaultRaw("NOW()");
|
|
3208
|
-
}
|
|
3209
|
-
softDeletes() {
|
|
3210
|
-
this.timestamp("deleted_at").nullable();
|
|
3211
|
-
}
|
|
3212
|
-
dropColumn(name) {
|
|
3213
|
-
this.droppedColumns.push(name);
|
|
3214
|
-
}
|
|
3215
|
-
dropSoftDeletes() {
|
|
3216
|
-
this.dropColumn("deleted_at");
|
|
3217
|
-
this.dropIndex(`idx_${this.table}_deleted_at`);
|
|
3218
|
-
}
|
|
3219
|
-
dropIndex(name) {
|
|
3220
|
-
this.droppedIndexes.push(name);
|
|
3221
|
-
}
|
|
3222
|
-
unique(columns, name) {
|
|
3223
|
-
this.indexes.push({
|
|
3224
|
-
name,
|
|
3225
|
-
columns: Array.isArray(columns) ? columns : [columns],
|
|
3226
|
-
kind: "unique"
|
|
3227
|
-
});
|
|
3228
|
-
}
|
|
3229
|
-
index(columns, options = {}) {
|
|
3230
|
-
this.indexes.push({
|
|
3231
|
-
name: options.name,
|
|
3232
|
-
columns: Array.isArray(columns) ? columns : [columns],
|
|
3233
|
-
kind: "index",
|
|
3234
|
-
order: options.order
|
|
3235
|
-
});
|
|
3236
|
-
}
|
|
3237
|
-
partialIndex(columns, where, nameOrOptions) {
|
|
3238
|
-
const options = typeof nameOrOptions === "string" ? { name: nameOrOptions } : nameOrOptions ?? {};
|
|
3239
|
-
this.indexes.push({
|
|
3240
|
-
name: options.name,
|
|
3241
|
-
columns: Array.isArray(columns) ? columns : [columns],
|
|
3242
|
-
kind: options.unique ? "uniquePartial" : "partial",
|
|
3243
|
-
where
|
|
3244
|
-
});
|
|
3245
|
-
}
|
|
3246
|
-
fullText(columns, name) {
|
|
3247
|
-
this.indexes.push({
|
|
3248
|
-
name,
|
|
3249
|
-
columns: Array.isArray(columns) ? columns : [columns],
|
|
3250
|
-
kind: "fullText"
|
|
3251
|
-
});
|
|
3252
|
-
}
|
|
3253
|
-
ginIndex(column, name) {
|
|
3254
|
-
this.indexes.push({
|
|
3255
|
-
name,
|
|
3256
|
-
columns: [column],
|
|
3257
|
-
kind: "gin"
|
|
3258
|
-
});
|
|
3259
|
-
}
|
|
3260
|
-
}
|
|
3261
|
-
// ../../src/core/database/schema/errors.ts
|
|
3262
|
-
class UnsupportedSchemaFeatureError extends Error {
|
|
3263
|
-
constructor(feature, driver) {
|
|
3264
|
-
super(`${feature} is not supported for the ${driver} driver`);
|
|
3265
|
-
this.name = "UnsupportedSchemaFeatureError";
|
|
3266
|
-
}
|
|
3267
|
-
}
|
|
3268
|
-
// ../../src/core/database/schema/grammars/grammar.ts
|
|
3269
|
-
function compileColumnType(driver, column) {
|
|
3270
|
-
switch (column.kind) {
|
|
3271
|
-
case "id":
|
|
3272
|
-
return compileIdType(driver);
|
|
3273
|
-
case "string":
|
|
3274
|
-
return compileStringType(driver, column.length);
|
|
3275
|
-
case "text":
|
|
3276
|
-
return compileTextType(driver);
|
|
3277
|
-
case "boolean":
|
|
3278
|
-
return compileBooleanType(driver);
|
|
3279
|
-
case "integer":
|
|
3280
|
-
case "foreignId":
|
|
3281
|
-
return compileIntegerType(driver);
|
|
3282
|
-
case "bigInteger":
|
|
3283
|
-
return compileBigIntegerType(driver);
|
|
3284
|
-
case "timestamp":
|
|
3285
|
-
return compileTimestampType(driver);
|
|
3286
|
-
case "json":
|
|
3287
|
-
return compileJsonType(driver);
|
|
3288
|
-
case "jsonb":
|
|
3289
|
-
return compileJsonbType(driver);
|
|
3290
|
-
default:
|
|
3291
|
-
throw new Error(`Unsupported column kind: ${column.kind}`);
|
|
3292
|
-
}
|
|
3293
|
-
}
|
|
3294
|
-
function compileIdType(driver) {
|
|
3295
|
-
switch (driver) {
|
|
3296
|
-
case "pgsql":
|
|
3297
|
-
return "SERIAL";
|
|
3298
|
-
case "mysql":
|
|
3299
|
-
return "BIGINT UNSIGNED";
|
|
3300
|
-
case "sqlite":
|
|
3301
|
-
return "INTEGER";
|
|
3302
|
-
}
|
|
3303
|
-
}
|
|
3304
|
-
function compileStringType(driver, length) {
|
|
3305
|
-
switch (driver) {
|
|
3306
|
-
case "pgsql":
|
|
3307
|
-
return "TEXT";
|
|
3308
|
-
case "mysql":
|
|
3309
|
-
return length ? `VARCHAR(${length})` : "VARCHAR(255)";
|
|
3310
|
-
case "sqlite":
|
|
3311
|
-
return "TEXT";
|
|
3312
|
-
}
|
|
3313
|
-
}
|
|
3314
|
-
function compileTextType(driver) {
|
|
3315
|
-
switch (driver) {
|
|
3316
|
-
case "pgsql":
|
|
3317
|
-
case "sqlite":
|
|
3318
|
-
return "TEXT";
|
|
3319
|
-
case "mysql":
|
|
3320
|
-
return "TEXT";
|
|
3321
|
-
}
|
|
3322
|
-
}
|
|
3323
|
-
function compileBooleanType(driver) {
|
|
3324
|
-
switch (driver) {
|
|
3325
|
-
case "pgsql":
|
|
3326
|
-
return "BOOLEAN";
|
|
3327
|
-
case "mysql":
|
|
3328
|
-
return "BOOLEAN";
|
|
3329
|
-
case "sqlite":
|
|
3330
|
-
return "INTEGER";
|
|
3331
|
-
}
|
|
3332
|
-
}
|
|
3333
|
-
function compileIntegerType(driver) {
|
|
3334
|
-
switch (driver) {
|
|
3335
|
-
case "pgsql":
|
|
3336
|
-
return "INTEGER";
|
|
3337
|
-
case "mysql":
|
|
3338
|
-
return "INT";
|
|
3339
|
-
case "sqlite":
|
|
3340
|
-
return "INTEGER";
|
|
3341
|
-
}
|
|
3342
|
-
}
|
|
3343
|
-
function compileBigIntegerType(driver) {
|
|
3344
|
-
switch (driver) {
|
|
3345
|
-
case "pgsql":
|
|
3346
|
-
return "BIGINT";
|
|
3347
|
-
case "mysql":
|
|
3348
|
-
return "BIGINT";
|
|
3349
|
-
case "sqlite":
|
|
3350
|
-
return "INTEGER";
|
|
3351
|
-
}
|
|
3352
|
-
}
|
|
3353
|
-
function compileTimestampType(driver) {
|
|
3354
|
-
switch (driver) {
|
|
3355
|
-
case "pgsql":
|
|
3356
|
-
return "TIMESTAMPTZ";
|
|
3357
|
-
case "mysql":
|
|
3358
|
-
return "TIMESTAMP";
|
|
3359
|
-
case "sqlite":
|
|
3360
|
-
return "TEXT";
|
|
3361
|
-
}
|
|
3362
|
-
}
|
|
3363
|
-
function compileJsonType(driver) {
|
|
3364
|
-
switch (driver) {
|
|
3365
|
-
case "pgsql":
|
|
3366
|
-
return "JSONB";
|
|
3367
|
-
case "mysql":
|
|
3368
|
-
return "JSON";
|
|
3369
|
-
case "sqlite":
|
|
3370
|
-
return "TEXT";
|
|
3371
|
-
}
|
|
3372
|
-
}
|
|
3373
|
-
function compileJsonbType(driver) {
|
|
3374
|
-
switch (driver) {
|
|
3375
|
-
case "pgsql":
|
|
3376
|
-
return "JSONB";
|
|
3377
|
-
case "mysql":
|
|
3378
|
-
return "JSON";
|
|
3379
|
-
case "sqlite":
|
|
3380
|
-
return "TEXT";
|
|
3381
|
-
}
|
|
3382
|
-
}
|
|
3383
|
-
|
|
3384
|
-
// ../../src/core/database/schema/grammars/compileStatements.ts
|
|
3385
|
-
function compileCreateTable(driver, blueprint) {
|
|
3386
|
-
const table = quoteIdentifier(blueprint.table);
|
|
3387
|
-
const parts = blueprint.columns.map((column) => compileColumn(driver, column, "create"));
|
|
3388
|
-
for (const index of blueprint.indexes) {
|
|
3389
|
-
if (index.kind === "unique" && index.columns.length > 1) {
|
|
3390
|
-
const columns = index.columns.map((column) => quoteIdentifier(column)).join(", ");
|
|
3391
|
-
parts.push(`UNIQUE (${columns})`);
|
|
3392
|
-
}
|
|
3393
|
-
}
|
|
3394
|
-
const statements = [`CREATE TABLE IF NOT EXISTS ${table} (
|
|
3395
|
-
${parts.join(`,
|
|
3396
|
-
`)}
|
|
3397
|
-
)`];
|
|
3398
|
-
for (const index of blueprint.indexes) {
|
|
3399
|
-
if (index.kind === "unique" && index.columns.length === 1) {
|
|
3400
|
-
continue;
|
|
3401
|
-
}
|
|
3402
|
-
if (index.kind === "index") {
|
|
3403
|
-
statements.push(compileIndex(driver, blueprint.table, index));
|
|
3404
|
-
} else if (index.kind === "partial" || index.kind === "uniquePartial" || index.kind === "gin" || index.kind === "fullText") {
|
|
3405
|
-
statements.push(...compileSpecialIndex(driver, blueprint.table, index));
|
|
3406
|
-
}
|
|
3407
|
-
}
|
|
3408
|
-
return statements;
|
|
3409
|
-
}
|
|
3410
|
-
function compileAlterTable(driver, blueprint) {
|
|
3411
|
-
const statements = [];
|
|
3412
|
-
const table = quoteIdentifier(blueprint.table);
|
|
3413
|
-
for (const column of blueprint.columns) {
|
|
3414
|
-
const addPrefix = driver === "pgsql" ? "ADD COLUMN IF NOT EXISTS" : "ADD COLUMN";
|
|
3415
|
-
statements.push(`ALTER TABLE ${table}
|
|
3416
|
-
${addPrefix} ${compileColumn(driver, column, "alter")}`);
|
|
3417
|
-
}
|
|
3418
|
-
for (const columnName of blueprint.droppedColumns) {
|
|
3419
|
-
const dropPrefix = driver === "pgsql" ? "DROP COLUMN IF EXISTS" : "DROP COLUMN";
|
|
3420
|
-
statements.push(`ALTER TABLE ${table} ${dropPrefix} ${quoteIdentifier(columnName)}`);
|
|
3421
|
-
}
|
|
3422
|
-
for (const indexName of blueprint.droppedIndexes) {
|
|
3423
|
-
statements.push(`DROP INDEX IF EXISTS ${quoteIdentifier(indexName)}`);
|
|
3424
|
-
}
|
|
3425
|
-
for (const index of blueprint.indexes) {
|
|
3426
|
-
if (index.kind === "index" || index.kind === "unique") {
|
|
3427
|
-
statements.push(compileIndex(driver, blueprint.table, index));
|
|
3428
|
-
} else {
|
|
3429
|
-
statements.push(...compileSpecialIndex(driver, blueprint.table, index));
|
|
3430
|
-
}
|
|
3431
|
-
}
|
|
3432
|
-
return statements;
|
|
3433
|
-
}
|
|
3434
|
-
function compileDropTable(driver, tableName) {
|
|
3435
|
-
const cascade = driver === "pgsql" ? " CASCADE" : "";
|
|
3436
|
-
return [`DROP TABLE IF EXISTS ${quoteIdentifier(tableName)}${cascade}`];
|
|
3437
|
-
}
|
|
3438
|
-
function compileColumn(driver, column, mode) {
|
|
3439
|
-
const parts = [quoteIdentifier(column.name), compileColumnType(driver, column)];
|
|
3440
|
-
if (column.autoIncrement && driver === "mysql") {
|
|
3441
|
-
parts[1] = `${parts[1]} AUTO_INCREMENT`;
|
|
3442
|
-
}
|
|
3443
|
-
if (column.isPrimary && mode === "create") {
|
|
3444
|
-
if (driver === "sqlite") {
|
|
3445
|
-
parts.push("PRIMARY KEY AUTOINCREMENT");
|
|
3446
|
-
} else {
|
|
3447
|
-
parts.push("PRIMARY KEY");
|
|
3448
|
-
}
|
|
3449
|
-
} else if (!column.isNullable) {
|
|
3450
|
-
parts.push("NOT NULL");
|
|
3451
|
-
} else if (column.isNullable) {
|
|
3452
|
-
parts.push("NULL");
|
|
3453
|
-
}
|
|
3454
|
-
if (column.defaultValue !== undefined) {
|
|
3455
|
-
parts.push(`DEFAULT ${column.defaultValue}`);
|
|
3456
|
-
}
|
|
3457
|
-
if (column.isUnique) {
|
|
3458
|
-
parts.push("UNIQUE");
|
|
3459
|
-
}
|
|
3460
|
-
if (column.checkExpression) {
|
|
3461
|
-
parts.push(`CHECK (${column.checkExpression})`);
|
|
3462
|
-
}
|
|
3463
|
-
if (column.foreignKey) {
|
|
3464
|
-
const { referencesTable, referencesColumn, onDelete } = column.foreignKey;
|
|
3465
|
-
const reference = `${quoteIdentifier(referencesTable)}(${quoteIdentifier(referencesColumn)})`;
|
|
3466
|
-
let clause = `REFERENCES ${reference}`;
|
|
3467
|
-
if (onDelete === "cascade") {
|
|
3468
|
-
clause += " ON DELETE CASCADE";
|
|
3469
|
-
} else if (onDelete === "set null") {
|
|
3470
|
-
clause += " ON DELETE SET NULL";
|
|
3471
|
-
}
|
|
3472
|
-
parts.push(clause);
|
|
3473
|
-
}
|
|
3474
|
-
return parts.join(" ");
|
|
3475
|
-
}
|
|
3476
|
-
function compileIndex(_driver, tableName, index) {
|
|
3477
|
-
const indexName = index.name ?? defaultIndexName(tableName, index.columns, index.kind === "unique" ? "unique" : "index");
|
|
3478
|
-
const columns = index.columns.map((column) => {
|
|
3479
|
-
const quoted = quoteIdentifier(column);
|
|
3480
|
-
if (index.order === "desc") {
|
|
3481
|
-
return `${quoted} DESC`;
|
|
3482
|
-
}
|
|
3483
|
-
return quoted;
|
|
3484
|
-
}).join(", ");
|
|
3485
|
-
const unique = index.kind === "unique" ? "UNIQUE " : "";
|
|
3486
|
-
return `CREATE ${unique}INDEX IF NOT EXISTS ${quoteIdentifier(indexName)} ON ${quoteIdentifier(tableName)}(${columns})`;
|
|
3487
|
-
}
|
|
3488
|
-
function compileSpecialIndex(driver, tableName, index) {
|
|
3489
|
-
const indexName = index.name ?? defaultIndexName(tableName, index.columns, index.kind);
|
|
3490
|
-
const columns = index.columns.map((column) => quoteIdentifier(column)).join(", ");
|
|
3491
|
-
switch (index.kind) {
|
|
3492
|
-
case "partial":
|
|
3493
|
-
case "uniquePartial": {
|
|
3494
|
-
if (driver !== "pgsql") {
|
|
3495
|
-
throw new UnsupportedSchemaFeatureError("partialIndex()", driver);
|
|
3496
|
-
}
|
|
3497
|
-
const unique = index.kind === "uniquePartial" ? "UNIQUE " : "";
|
|
3498
|
-
return [
|
|
3499
|
-
`CREATE ${unique}INDEX IF NOT EXISTS ${quoteIdentifier(indexName)} ON ${quoteIdentifier(tableName)}(${columns}) WHERE ${index.where}`
|
|
3500
|
-
];
|
|
3501
|
-
}
|
|
3502
|
-
case "gin": {
|
|
3503
|
-
if (driver !== "pgsql") {
|
|
3504
|
-
throw new UnsupportedSchemaFeatureError("ginIndex()", driver);
|
|
3505
|
-
}
|
|
3506
|
-
return [
|
|
3507
|
-
`CREATE INDEX IF NOT EXISTS ${quoteIdentifier(indexName)} ON ${quoteIdentifier(tableName)} USING GIN(${columns})`
|
|
3508
|
-
];
|
|
3509
|
-
}
|
|
3510
|
-
case "fullText": {
|
|
3511
|
-
if (driver === "mysql") {
|
|
3512
|
-
return [
|
|
3513
|
-
`CREATE FULLTEXT INDEX ${quoteIdentifier(indexName)} ON ${quoteIdentifier(tableName)}(${columns})`
|
|
3514
|
-
];
|
|
3515
|
-
}
|
|
3516
|
-
if (driver === "pgsql") {
|
|
3517
|
-
throw new UnsupportedSchemaFeatureError("fullText(); use ginIndex() with a tsvector column on PostgreSQL", driver);
|
|
3518
|
-
}
|
|
3519
|
-
throw new UnsupportedSchemaFeatureError("fullText()", driver);
|
|
3520
|
-
}
|
|
3521
|
-
default:
|
|
3522
|
-
return [];
|
|
3523
|
-
}
|
|
3524
|
-
}
|
|
3525
|
-
function defaultIndexName(tableName, columns, kind) {
|
|
3526
|
-
return `idx_${tableName}_${columns.join("_")}_${kind}`;
|
|
3527
|
-
}
|
|
3528
|
-
function compileBlueprint(driver, blueprint) {
|
|
3529
|
-
switch (blueprint.action) {
|
|
3530
|
-
case "create":
|
|
3531
|
-
return compileCreateTable(driver, blueprint);
|
|
3532
|
-
case "alter":
|
|
3533
|
-
return compileAlterTable(driver, blueprint);
|
|
3534
|
-
case "drop":
|
|
3535
|
-
return compileDropTable(driver, blueprint.table);
|
|
3536
|
-
default:
|
|
3537
|
-
throw new Error(`Unsupported blueprint action: ${blueprint.action}`);
|
|
3538
|
-
}
|
|
3539
|
-
}
|
|
3540
|
-
// ../../src/core/database/schema/grammars/createGrammar.ts
|
|
3541
|
-
function createGrammar(driver) {
|
|
3542
|
-
return {
|
|
3543
|
-
driver,
|
|
3544
|
-
compile(blueprint) {
|
|
3545
|
-
return compileBlueprint(driver, blueprint);
|
|
3546
|
-
}
|
|
3547
|
-
};
|
|
3548
|
-
}
|
|
3549
|
-
|
|
3550
|
-
// ../../src/core/database/schema/grammars/mysqlGrammar.ts
|
|
3551
|
-
var MySqlGrammar = createGrammar("mysql");
|
|
3552
|
-
|
|
3553
|
-
// ../../src/core/database/schema/grammars/postgresGrammar.ts
|
|
3554
|
-
var PostgresGrammar = createGrammar("pgsql");
|
|
3555
|
-
|
|
3556
|
-
// ../../src/core/database/schema/grammars/sqliteGrammar.ts
|
|
3557
|
-
var SqliteGrammar = createGrammar("sqlite");
|
|
3558
|
-
|
|
3559
|
-
// ../../src/core/database/schema/grammars/index.ts
|
|
3560
|
-
function grammarForDriver(driver) {
|
|
3561
|
-
switch (driver) {
|
|
3562
|
-
case "pgsql":
|
|
3563
|
-
return PostgresGrammar;
|
|
3564
|
-
case "mysql":
|
|
3565
|
-
return MySqlGrammar;
|
|
3566
|
-
case "sqlite":
|
|
3567
|
-
return SqliteGrammar;
|
|
3568
|
-
default:
|
|
3569
|
-
throw new Error(`Unsupported database driver: ${driver}`);
|
|
3570
|
-
}
|
|
3571
|
-
}
|
|
3572
|
-
// ../../src/core/database/schema/schema.ts
|
|
3573
|
-
class SchemaBuilder {
|
|
3574
|
-
#driver;
|
|
3575
|
-
#statements = [];
|
|
3576
|
-
constructor(driver) {
|
|
3577
|
-
this.#driver = driver;
|
|
3578
|
-
}
|
|
3579
|
-
create(table, callback) {
|
|
3580
|
-
const blueprint = new Blueprint(table, "create");
|
|
3581
|
-
callback(blueprint);
|
|
3582
|
-
this.#statements.push(...grammarForDriver(this.#driver).compile(blueprint));
|
|
3583
|
-
return this;
|
|
3584
|
-
}
|
|
3585
|
-
table(table, callback) {
|
|
3586
|
-
const blueprint = new Blueprint(table, "alter");
|
|
3587
|
-
callback(blueprint);
|
|
3588
|
-
this.#statements.push(...grammarForDriver(this.#driver).compile(blueprint));
|
|
3589
|
-
return this;
|
|
3590
|
-
}
|
|
3591
|
-
drop(table) {
|
|
3592
|
-
const blueprint = new Blueprint(table, "drop");
|
|
3593
|
-
this.#statements.push(...grammarForDriver(this.#driver).compile(blueprint));
|
|
3594
|
-
return this;
|
|
3595
|
-
}
|
|
3596
|
-
toSql() {
|
|
3597
|
-
return [...this.#statements];
|
|
3598
|
-
}
|
|
3599
|
-
async execute(db2) {
|
|
3600
|
-
for (const statement of this.#statements) {
|
|
3601
|
-
await db2.unsafe(statement);
|
|
3602
|
-
}
|
|
3603
|
-
}
|
|
3604
|
-
}
|
|
3605
|
-
// ../../src/core/database/table.ts
|
|
3606
|
-
function defineTable5(definition) {
|
|
3607
|
-
return definition;
|
|
3608
|
-
}
|
|
3609
|
-
// ../../src/core/queue/failedJobTable.ts
|
|
3610
|
-
var failedJobTable = defineTable5({
|
|
3611
|
-
name: "failed_job",
|
|
3612
|
-
primaryKey: "id",
|
|
3613
|
-
columns: ["id", "job_name", "payload", "exception", "failed_at"],
|
|
3614
|
-
defaultOrderBy: { column: "failed_at", direction: "DESC" }
|
|
3615
|
-
});
|
|
3616
|
-
|
|
3617
|
-
// ../../src/core/queue/failedJobRepository.ts
|
|
3618
|
-
class FailedJobRepository extends baseRepository_default {
|
|
3619
|
-
constructor() {
|
|
3620
|
-
super(failedJobTable);
|
|
3621
|
-
}
|
|
3622
|
-
}
|
|
3623
|
-
var failedJobRepository_default = FailedJobRepository;
|
|
3624
|
-
|
|
3625
|
-
// ../../src/core/queue/failedJobService.ts
|
|
3626
|
-
class FailedJobService {
|
|
3627
|
-
repository;
|
|
3628
|
-
constructor(repository) {
|
|
3629
|
-
this.repository = repository;
|
|
3630
|
-
}
|
|
3631
|
-
async recordFailure(input) {
|
|
3632
|
-
return await this.repository.create({
|
|
3633
|
-
job_name: input.jobName,
|
|
3634
|
-
payload: input.payload,
|
|
3635
|
-
exception: input.exception,
|
|
3636
|
-
failed_at: new Date
|
|
3637
|
-
});
|
|
3638
|
-
}
|
|
3639
|
-
listRecent(limit = 50) {
|
|
3640
|
-
return this.repository.findAll({
|
|
3641
|
-
limit,
|
|
3642
|
-
orderBy: { column: "failed_at", direction: "DESC" }
|
|
3643
|
-
});
|
|
3644
|
-
}
|
|
3645
|
-
async retry(id) {
|
|
3646
|
-
const failedJob = await this.repository.findByIdOrThrow(id, (jobId) => new Error(`Failed job ${jobId} not found.`));
|
|
3647
|
-
await this.repository.deleteById(id);
|
|
3648
|
-
return failedJob;
|
|
3649
|
-
}
|
|
3650
|
-
async delete(id) {
|
|
3651
|
-
const deleted = await this.repository.deleteById(id);
|
|
3652
|
-
if (!deleted) {
|
|
3653
|
-
throw new Error(`Failed job ${id} not found.`);
|
|
3654
|
-
}
|
|
3655
|
-
}
|
|
3656
|
-
async flush() {
|
|
3657
|
-
const jobs = await this.repository.findAll();
|
|
3658
|
-
let deleted = 0;
|
|
3659
|
-
for (const job of jobs) {
|
|
3660
|
-
if (await this.repository.deleteById(job.id)) {
|
|
3661
|
-
deleted += 1;
|
|
3662
|
-
}
|
|
3663
|
-
}
|
|
3664
|
-
return deleted;
|
|
3665
|
-
}
|
|
3666
|
-
}
|
|
3667
|
-
var failedJobService_default = FailedJobService;
|
|
3668
|
-
|
|
3669
|
-
// ../../src/core/queue/jobRegistry.ts
|
|
3670
|
-
class JobRegistry {
|
|
3671
|
-
factories = new Map;
|
|
3672
|
-
instances = new WeakMap;
|
|
3673
|
-
register(name, factory) {
|
|
3674
|
-
this.factories.set(name, factory);
|
|
3675
|
-
}
|
|
3676
|
-
resolveName(job) {
|
|
3677
|
-
return this.instances.get(job);
|
|
3678
|
-
}
|
|
3679
|
-
track(name, job) {
|
|
3680
|
-
this.instances.set(job, name);
|
|
3681
|
-
return job;
|
|
3682
|
-
}
|
|
3683
|
-
create(name) {
|
|
3684
|
-
const factory = this.factories.get(name);
|
|
3685
|
-
if (!factory) {
|
|
3686
|
-
return;
|
|
3687
|
-
}
|
|
3688
|
-
return factory();
|
|
3689
|
-
}
|
|
3690
|
-
names() {
|
|
3691
|
-
return [...this.factories.keys()];
|
|
3692
|
-
}
|
|
3693
|
-
}
|
|
3694
|
-
var JOB_REGISTRY_KEY = Symbol.for("@getstrata/jobRegistry");
|
|
3695
|
-
function readSharedJobRegistry() {
|
|
3696
|
-
const globalRegistry = globalThis[JOB_REGISTRY_KEY];
|
|
3697
|
-
if (globalRegistry) {
|
|
3698
|
-
return globalRegistry;
|
|
3699
|
-
}
|
|
3700
|
-
const registry = new JobRegistry;
|
|
3701
|
-
globalThis[JOB_REGISTRY_KEY] = registry;
|
|
3702
|
-
return registry;
|
|
3703
|
-
}
|
|
3704
|
-
var jobRegistry = readSharedJobRegistry();
|
|
3705
|
-
|
|
3706
|
-
// ../../src/core/queue/jobRunner.ts
|
|
3707
|
-
async function runQueueJob(envelope, failedJobs) {
|
|
3708
|
-
const job = jobRegistry.create(envelope.name);
|
|
3709
|
-
if (!job) {
|
|
3710
|
-
throw new Error(`Unknown job "${envelope.name}".`);
|
|
3711
|
-
}
|
|
3712
|
-
const attempts = envelope.attempts ?? 0;
|
|
3713
|
-
try {
|
|
3714
|
-
await job.handle(envelope.payload);
|
|
3715
|
-
} catch (error) {
|
|
3716
|
-
const nextAttempt = attempts + 1;
|
|
3717
|
-
const maxAttempts = job.maxAttempts ?? queueConfig.maxAttempts;
|
|
3718
|
-
if (nextAttempt < maxAttempts) {
|
|
3719
|
-
const backoffMs = job.backoffMs ?? queueConfig.backoffMs;
|
|
3720
|
-
await new Promise((resolve) => setTimeout(resolve, backoffMs * nextAttempt));
|
|
3721
|
-
await runQueueJob({
|
|
3722
|
-
...envelope,
|
|
3723
|
-
attempts: nextAttempt
|
|
3724
|
-
}, failedJobs);
|
|
3725
|
-
return;
|
|
3726
|
-
}
|
|
3727
|
-
await failedJobs.recordFailure({
|
|
3728
|
-
jobName: envelope.name,
|
|
3729
|
-
payload: envelope.payload,
|
|
3730
|
-
exception: error instanceof Error ? error.stack ?? error.message : String(error)
|
|
3731
|
-
});
|
|
3732
|
-
throw error;
|
|
3733
|
-
}
|
|
3734
|
-
}
|
|
3735
|
-
|
|
3736
|
-
// ../../src/core/queue/redisQueue.ts
|
|
3737
|
-
var {RedisClient: RedisClient2 } = globalThis.Bun;
|
|
3738
|
-
var QUEUE_LIST_KEY = "workhub:queue:default";
|
|
3739
|
-
var QUEUE_HIGH_KEY = "workhub:queue:high";
|
|
3740
|
-
var QUEUE_LOW_KEY = "workhub:queue:low";
|
|
3741
|
-
function queueKeyForPriority(priority = "default") {
|
|
3742
|
-
switch (priority) {
|
|
3743
|
-
case "high":
|
|
3744
|
-
return QUEUE_HIGH_KEY;
|
|
3745
|
-
case "low":
|
|
3746
|
-
return QUEUE_LOW_KEY;
|
|
3747
|
-
default:
|
|
3748
|
-
return QUEUE_LIST_KEY;
|
|
3749
|
-
}
|
|
3750
|
-
}
|
|
3751
|
-
class RedisQueue {
|
|
3752
|
-
client;
|
|
3753
|
-
constructor(redisUrl) {
|
|
3754
|
-
this.client = new RedisClient2(redisUrl);
|
|
3755
|
-
}
|
|
3756
|
-
async dispatch(job, payload) {
|
|
3757
|
-
const name = jobRegistry.resolveName(job);
|
|
3758
|
-
if (!name) {
|
|
3759
|
-
throw new Error("Job is not registered with the queue worker registry.");
|
|
3760
|
-
}
|
|
3761
|
-
const envelope = {
|
|
3762
|
-
name,
|
|
3763
|
-
payload,
|
|
3764
|
-
attempts: 0
|
|
3765
|
-
};
|
|
3766
|
-
const queueKey = queueKeyForPriority(job.priority);
|
|
3767
|
-
await this.client.lpush(queueKey, JSON.stringify(envelope));
|
|
3768
|
-
}
|
|
3769
|
-
}
|
|
3770
|
-
|
|
3771
|
-
// ../../src/core/queue/resilientQueue.ts
|
|
3772
|
-
class ResilientQueue {
|
|
3773
|
-
failedJobs;
|
|
3774
|
-
asyncDispatch;
|
|
3775
|
-
constructor(failedJobs, asyncDispatch = false) {
|
|
3776
|
-
this.failedJobs = failedJobs;
|
|
3777
|
-
this.asyncDispatch = asyncDispatch;
|
|
3778
|
-
}
|
|
3779
|
-
async dispatch(job, payload) {
|
|
3780
|
-
const name = jobRegistry.resolveName(job);
|
|
3781
|
-
if (!name) {
|
|
3782
|
-
throw new Error("Job is not registered with the queue worker registry.");
|
|
3783
|
-
}
|
|
3784
|
-
const envelope = {
|
|
3785
|
-
name,
|
|
3786
|
-
payload,
|
|
3787
|
-
attempts: 0
|
|
3788
|
-
};
|
|
3789
|
-
if (this.asyncDispatch) {
|
|
3790
|
-
setTimeout(() => {
|
|
3791
|
-
runQueueJob(envelope, this.failedJobs).catch((error) => {
|
|
3792
|
-
console.error("[ResilientQueue] Job failed:", error);
|
|
3793
|
-
});
|
|
3794
|
-
}, 0);
|
|
3795
|
-
return;
|
|
3796
|
-
}
|
|
3797
|
-
await runQueueJob(envelope, this.failedJobs);
|
|
3798
|
-
}
|
|
3799
|
-
}
|
|
3800
|
-
|
|
3801
|
-
// ../../src/core/queue/publicQueue.ts
|
|
3802
|
-
function createFailedJobService() {
|
|
3803
|
-
return new failedJobService_default(new failedJobRepository_default);
|
|
3804
|
-
}
|
|
3805
|
-
function createProductionQueue(driver, options = {}) {
|
|
3806
|
-
options.registerJobs?.();
|
|
3807
|
-
const failedJobs = options.failedJobs ?? createFailedJobService();
|
|
3808
|
-
if (driver === "redis") {
|
|
3809
|
-
if (!options.redisUrl) {
|
|
3810
|
-
throw new Error('QUEUE_DRIVER="redis" requires REDIS_URL to be set.');
|
|
3811
|
-
}
|
|
3812
|
-
return new RedisQueue(options.redisUrl);
|
|
3813
|
-
}
|
|
3814
|
-
return new ResilientQueue(failedJobs, driver === "async");
|
|
3815
|
-
}
|
|
3816
|
-
|
|
3817
|
-
// ../../src/core/queue/createAppQueue.ts
|
|
3818
|
-
var FAILED_JOB_SERVICE_TOKEN = "core.failedJobs";
|
|
3819
|
-
function createAppQueue(driver, redisUrl, failedJobs = createFailedJobService(), registerJobs) {
|
|
3820
|
-
return createProductionQueue(driver, {
|
|
3821
|
-
redisUrl,
|
|
3822
|
-
failedJobs,
|
|
3823
|
-
registerJobs
|
|
3824
|
-
});
|
|
3825
|
-
}
|
|
3826
|
-
|
|
3827
|
-
// ../../src/core/jobs/dispatchWebhookJob.ts
|
|
3828
|
-
import { createHmac as createHmac2 } from "crypto";
|
|
3829
|
-
|
|
3830
|
-
// ../../src/core/queue/index.ts
|
|
3831
|
-
class Job {
|
|
3832
|
-
maxAttempts;
|
|
3833
|
-
backoffMs;
|
|
3834
|
-
priority;
|
|
3835
|
-
}
|
|
3836
|
-
|
|
3837
|
-
// ../../src/core/security/safeUrl.ts
|
|
3838
|
-
import { lookup as dnsLookupImpl } from "dns/promises";
|
|
3839
|
-
var dnsLookup = dnsLookupImpl;
|
|
3840
|
-
var BLOCKED_HOSTNAMES = new Set([
|
|
3841
|
-
"localhost",
|
|
3842
|
-
"127.0.0.1",
|
|
3843
|
-
"0.0.0.0",
|
|
3844
|
-
"::1",
|
|
3845
|
-
"metadata.google.internal"
|
|
3846
|
-
]);
|
|
3847
|
-
function isPrivateIpv4(hostname) {
|
|
3848
|
-
const match = /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/.exec(hostname);
|
|
3849
|
-
if (!match) {
|
|
3850
|
-
return false;
|
|
3851
|
-
}
|
|
3852
|
-
const octets = match.slice(1, 5).map((part) => Number.parseInt(part, 10));
|
|
3853
|
-
if (octets.some((octet) => octet < 0 || octet > 255)) {
|
|
3854
|
-
return true;
|
|
3855
|
-
}
|
|
3856
|
-
const [a = 0, b = 0] = octets;
|
|
3857
|
-
if (a === 10) {
|
|
3858
|
-
return true;
|
|
3859
|
-
}
|
|
3860
|
-
if (a === 127) {
|
|
3861
|
-
return true;
|
|
3862
|
-
}
|
|
3863
|
-
if (a === 0) {
|
|
3864
|
-
return true;
|
|
3865
|
-
}
|
|
3866
|
-
if (a === 169 && b === 254) {
|
|
3867
|
-
return true;
|
|
3868
|
-
}
|
|
3869
|
-
if (a === 172 && b >= 16 && b <= 31) {
|
|
3870
|
-
return true;
|
|
3871
|
-
}
|
|
3872
|
-
if (a === 192 && b === 168) {
|
|
3873
|
-
return true;
|
|
3874
|
-
}
|
|
3875
|
-
return false;
|
|
3876
|
-
}
|
|
3877
|
-
function isBlockedHostname(hostname) {
|
|
3878
|
-
const normalized = hostname.trim().toLowerCase();
|
|
3879
|
-
if (normalized.length === 0) {
|
|
3880
|
-
return true;
|
|
3881
|
-
}
|
|
3882
|
-
if (BLOCKED_HOSTNAMES.has(normalized)) {
|
|
3883
|
-
return true;
|
|
3884
|
-
}
|
|
3885
|
-
if (normalized.endsWith(".local") || normalized.endsWith(".internal")) {
|
|
3886
|
-
return true;
|
|
3887
|
-
}
|
|
3888
|
-
if (normalized.includes(":")) {
|
|
3889
|
-
return true;
|
|
3890
|
-
}
|
|
3891
|
-
return isPrivateIpv4(normalized);
|
|
3892
|
-
}
|
|
3893
|
-
function assertSafeOutboundUrl(rawUrl, options = {}) {
|
|
3894
|
-
let parsed;
|
|
3895
|
-
try {
|
|
3896
|
-
parsed = new URL(rawUrl);
|
|
3897
|
-
} catch {
|
|
3898
|
-
throw new BadRequestError("Webhook URL is invalid.");
|
|
3899
|
-
}
|
|
3900
|
-
if (parsed.protocol !== "https:" && !(options.allowHttp && parsed.protocol === "http:")) {
|
|
3901
|
-
throw new BadRequestError("Webhook URL must use HTTPS.");
|
|
3902
|
-
}
|
|
3903
|
-
if (parsed.username || parsed.password) {
|
|
3904
|
-
throw new BadRequestError("Webhook URL must not include credentials.");
|
|
3905
|
-
}
|
|
3906
|
-
if (isBlockedHostname(parsed.hostname)) {
|
|
3907
|
-
throw new BadRequestError("Webhook URL targets a blocked host.");
|
|
3908
|
-
}
|
|
3909
|
-
return parsed;
|
|
3910
|
-
}
|
|
3911
|
-
function isBlockedIpAddress(address) {
|
|
3912
|
-
return isBlockedHostname(address.trim().toLowerCase());
|
|
3913
|
-
}
|
|
3914
|
-
async function assertSafeOutboundUrlResolved(rawUrl, options = {}) {
|
|
3915
|
-
const parsed = assertSafeOutboundUrl(rawUrl, options);
|
|
3916
|
-
if (options.resolveDns === false) {
|
|
3917
|
-
return parsed;
|
|
3918
|
-
}
|
|
3919
|
-
const hostname = parsed.hostname.trim().toLowerCase();
|
|
3920
|
-
const results = await dnsLookup(hostname, { all: true, verbatim: true });
|
|
3921
|
-
if (results.some((result) => isBlockedIpAddress(result.address))) {
|
|
3922
|
-
throw new BadRequestError("Webhook URL targets a blocked host.");
|
|
3923
|
-
}
|
|
3924
|
-
return parsed;
|
|
3925
|
-
}
|
|
3926
|
-
|
|
3927
|
-
// ../../src/core/security/safeFetch.ts
|
|
3928
|
-
var DEFAULT_FETCH_TIMEOUT_MS = 1e4;
|
|
3929
|
-
async function safeFetch(input, init = {}, options = {}) {
|
|
3930
|
-
const timeoutMs = options.timeoutMs ?? DEFAULT_FETCH_TIMEOUT_MS;
|
|
3931
|
-
const maxRedirects = options.maxRedirects ?? 0;
|
|
3932
|
-
const resolveDns = options.resolveDns ?? appConfig.env === "production";
|
|
3933
|
-
const urlOptions = { allowHttp: options.allowHttp, resolveDns };
|
|
3934
|
-
const controller = new AbortController;
|
|
3935
|
-
const timeout = setTimeout(() => controller.abort(), timeoutMs);
|
|
3936
|
-
try {
|
|
3937
|
-
let currentUrl = (await assertSafeOutboundUrlResolved(input, urlOptions)).toString();
|
|
3938
|
-
let redirectCount = 0;
|
|
3939
|
-
while (true) {
|
|
3940
|
-
const response = await fetch(currentUrl, {
|
|
3941
|
-
...init,
|
|
3942
|
-
signal: controller.signal,
|
|
3943
|
-
redirect: "manual"
|
|
3944
|
-
});
|
|
3945
|
-
if (response.status >= 300 && response.status < 400) {
|
|
3946
|
-
const location = response.headers.get("location");
|
|
3947
|
-
if (!location || redirectCount >= maxRedirects) {
|
|
3948
|
-
return response;
|
|
3949
|
-
}
|
|
3950
|
-
currentUrl = (await assertSafeOutboundUrlResolved(new URL(location, currentUrl).toString(), urlOptions)).toString();
|
|
3951
|
-
redirectCount += 1;
|
|
3952
|
-
continue;
|
|
3953
|
-
}
|
|
3954
|
-
return response;
|
|
3955
|
-
}
|
|
3956
|
-
} finally {
|
|
3957
|
-
clearTimeout(timeout);
|
|
3958
|
-
}
|
|
3959
|
-
}
|
|
3960
|
-
|
|
3961
|
-
// ../../src/core/jobs/dispatchWebhookJob.ts
|
|
3962
|
-
class DispatchWebhookJob extends Job {
|
|
3963
|
-
maxAttempts = 3;
|
|
3964
|
-
backoffMs = 2000;
|
|
3965
|
-
async handle(payload) {
|
|
3966
|
-
const rows = await repositoryConnection`
|
|
3967
|
-
SELECT id, url, secret
|
|
3968
|
-
FROM webhook
|
|
3969
|
-
WHERE id = ${payload.webhookId} AND active = TRUE
|
|
3970
|
-
LIMIT 1
|
|
3971
|
-
`;
|
|
3972
|
-
const webhook = rows[0];
|
|
3973
|
-
if (!webhook) {
|
|
3974
|
-
return;
|
|
3975
|
-
}
|
|
3976
|
-
const body = JSON.stringify({ event: payload.event, payload: payload.payload });
|
|
3977
|
-
const signature = createHmac2("sha256", webhook.secret).update(body).digest("hex");
|
|
3978
|
-
assertSafeOutboundUrl(webhook.url, { allowHttp: appConfig.env !== "production" });
|
|
3979
|
-
let responseStatus = null;
|
|
3980
|
-
let errorMessage = null;
|
|
3981
|
-
try {
|
|
3982
|
-
const response = await safeFetch(webhook.url, {
|
|
3983
|
-
method: "POST",
|
|
3984
|
-
headers: {
|
|
3985
|
-
"content-type": "application/json",
|
|
3986
|
-
"x-workhub-signature": signature
|
|
3987
|
-
},
|
|
3988
|
-
body
|
|
3989
|
-
}, { allowHttp: appConfig.env !== "production" });
|
|
3990
|
-
responseStatus = response.status;
|
|
3991
|
-
if (!response.ok) {
|
|
3992
|
-
throw new Error(`Webhook delivery failed with status ${response.status}.`);
|
|
3993
|
-
}
|
|
3994
|
-
} catch (error) {
|
|
3995
|
-
errorMessage = error instanceof Error ? error.message : String(error);
|
|
3996
|
-
await repositoryConnection`
|
|
3997
|
-
INSERT INTO webhook_delivery (webhook_id, event, payload, response_status, error)
|
|
3998
|
-
VALUES (
|
|
3999
|
-
${webhook.id},
|
|
4000
|
-
${payload.event},
|
|
4001
|
-
${JSON.stringify(payload.payload)}::jsonb,
|
|
4002
|
-
${responseStatus},
|
|
4003
|
-
${errorMessage}
|
|
4004
|
-
)
|
|
4005
|
-
`;
|
|
4006
|
-
throw error instanceof Error ? error : new Error(errorMessage);
|
|
4007
|
-
}
|
|
4008
|
-
await repositoryConnection`
|
|
4009
|
-
INSERT INTO webhook_delivery (webhook_id, event, payload, response_status)
|
|
4010
|
-
VALUES (
|
|
4011
|
-
${webhook.id},
|
|
4012
|
-
${payload.event},
|
|
4013
|
-
${JSON.stringify(payload.payload)}::jsonb,
|
|
4014
|
-
${responseStatus}
|
|
4015
|
-
)
|
|
4016
|
-
`;
|
|
4017
|
-
}
|
|
4018
|
-
}
|
|
4019
|
-
var dispatchWebhookJob_default = DispatchWebhookJob;
|
|
4020
|
-
|
|
4021
|
-
// ../../src/core/jobs/invalidateCacheTagsJob.ts
|
|
4022
|
-
class InvalidateCacheTagsJob2 extends Job {
|
|
4023
|
-
cache;
|
|
4024
|
-
constructor(cache) {
|
|
4025
|
-
super();
|
|
4026
|
-
this.cache = cache;
|
|
4027
|
-
}
|
|
4028
|
-
async handle(payload) {
|
|
4029
|
-
await this.cache.tags(...payload.tags).flush();
|
|
4030
|
-
}
|
|
4031
|
-
}
|
|
4032
|
-
var invalidateCacheTagsJob_default = InvalidateCacheTagsJob2;
|
|
4033
|
-
|
|
4034
|
-
// ../../src/core/contracts/di.ts
|
|
4035
|
-
function getRequiredDependency2(dependencies, key) {
|
|
4036
|
-
const dependency = dependencies[key];
|
|
4037
|
-
if (dependency === undefined) {
|
|
4038
|
-
throw new Error(`Required dependency "${key}" is not registered.`);
|
|
4039
|
-
}
|
|
4040
|
-
return dependency;
|
|
4041
|
-
}
|
|
4042
|
-
|
|
4043
|
-
// ../../src/core/contracts/serviceTokens.ts
|
|
4044
|
-
var CORE_POLICY_GATE_TOKEN2 = "core.policyGate";
|
|
4045
|
-
var CORE_AUTH_TOKEN2 = "core.auth";
|
|
4046
|
-
|
|
4047
|
-
// ../../src/core/logging/logger.ts
|
|
4048
|
-
class Logger {
|
|
4049
|
-
channel;
|
|
4050
|
-
constructor(channel = "app") {
|
|
4051
|
-
this.channel = channel;
|
|
4052
|
-
}
|
|
4053
|
-
write(level, message, context = {}) {
|
|
4054
|
-
const entry = {
|
|
4055
|
-
level,
|
|
4056
|
-
channel: this.channel,
|
|
4057
|
-
message,
|
|
4058
|
-
timestamp: new Date().toISOString(),
|
|
4059
|
-
...context
|
|
4060
|
-
};
|
|
4061
|
-
const line = JSON.stringify(entry);
|
|
4062
|
-
if (level === "error") {
|
|
4063
|
-
console.error(line);
|
|
4064
|
-
return;
|
|
4065
|
-
}
|
|
4066
|
-
console.log(line);
|
|
4067
|
-
}
|
|
4068
|
-
debug(message, context) {
|
|
4069
|
-
this.write("debug", message, context);
|
|
4070
|
-
}
|
|
4071
|
-
info(message, context) {
|
|
4072
|
-
this.write("info", message, context);
|
|
4073
|
-
}
|
|
4074
|
-
warn(message, context) {
|
|
4075
|
-
this.write("warn", message, context);
|
|
4076
|
-
}
|
|
4077
|
-
error(message, context) {
|
|
4078
|
-
this.write("error", message, context);
|
|
4079
|
-
}
|
|
4080
|
-
}
|
|
4081
|
-
var appLogger2 = new Logger("app");
|
|
4082
|
-
|
|
4083
|
-
// ../../src/core/runtime/applicationRegistry.ts
|
|
4084
|
-
var APPLICATION_CONTEXT_KEY = Symbol.for("@getstrata/applicationContext");
|
|
4085
|
-
var activeContext;
|
|
4086
|
-
function readStoredApplicationContext() {
|
|
4087
|
-
if (activeContext) {
|
|
4088
|
-
return activeContext;
|
|
4089
|
-
}
|
|
4090
|
-
const globalContext = globalThis[APPLICATION_CONTEXT_KEY];
|
|
4091
|
-
if (globalContext) {
|
|
4092
|
-
activeContext = globalContext;
|
|
4093
|
-
}
|
|
4094
|
-
return activeContext;
|
|
4095
|
-
}
|
|
4096
|
-
function requireActiveApplicationContext() {
|
|
4097
|
-
const context = readStoredApplicationContext();
|
|
4098
|
-
if (!context) {
|
|
4099
|
-
throw new Error("The application context has not been bootstrapped.");
|
|
4100
|
-
}
|
|
4101
|
-
return context;
|
|
4102
|
-
}
|
|
4103
|
-
function resolveApplicationCache2() {
|
|
4104
|
-
return getRequiredDependency2(requireActiveApplicationContext().dependencies, "cache");
|
|
4105
|
-
}
|
|
4106
|
-
function resolveApplicationAuth2() {
|
|
4107
|
-
return requireActiveApplicationContext().container.resolve(CORE_AUTH_TOKEN2);
|
|
4108
|
-
}
|
|
4109
|
-
function resolveApplicationPolicyGate2() {
|
|
4110
|
-
return requireActiveApplicationContext().container.resolve(CORE_POLICY_GATE_TOKEN2);
|
|
4111
|
-
}
|
|
4112
|
-
|
|
4113
|
-
// ../../src/bootstrap/queue/defaultJobs.ts
|
|
4114
|
-
function registerDefaultJobs() {
|
|
4115
|
-
jobRegistry.register("cache.invalidate-tags", () => {
|
|
4116
|
-
return new invalidateCacheTagsJob_default(resolveApplicationCache2());
|
|
4117
|
-
});
|
|
4118
|
-
jobRegistry.register("webhook.dispatch", () => new dispatchWebhookJob_default);
|
|
4119
|
-
}
|
|
4120
|
-
|
|
4121
|
-
// ../../src/bootstrap/providers/queue.ts
|
|
4122
|
-
var queueProvider = {
|
|
4123
|
-
name: "core.queue",
|
|
4124
|
-
register({ container, config }) {
|
|
4125
|
-
const configuredDriver = process.env.QUEUE_DRIVER ?? DEFAULT_QUEUE_DRIVER;
|
|
4126
|
-
const driver = configuredDriver === "async" || configuredDriver === "redis" || configuredDriver === "sync" ? configuredDriver : DEFAULT_QUEUE_DRIVER;
|
|
4127
|
-
config.set("queue.driver", driver);
|
|
4128
|
-
const failedJobs = createFailedJobService();
|
|
4129
|
-
container.set(FAILED_JOB_SERVICE_TOKEN, failedJobs);
|
|
4130
|
-
container.set(CORE_QUEUE_TOKEN, createAppQueue(driver, config.get(REDIS_URL_CONFIG_KEY) ?? process.env.REDIS_URL, failedJobs, registerDefaultJobs));
|
|
4131
|
-
}
|
|
4132
|
-
};
|
|
4133
|
-
var queue_default = queueProvider;
|
|
4134
|
-
|
|
4135
|
-
// ../../src/core/storage/storage.ts
|
|
4136
|
-
import { mkdir, readFile, unlink, writeFile } from "fs/promises";
|
|
4137
|
-
import { dirname, join as join3 } from "path";
|
|
4138
|
-
var {S3Client } = globalThis.Bun;
|
|
4139
|
-
|
|
4140
|
-
class LocalStorageDriver {
|
|
4141
|
-
rootDirectory;
|
|
4142
|
-
constructor(rootDirectory) {
|
|
4143
|
-
this.rootDirectory = rootDirectory;
|
|
4144
|
-
}
|
|
4145
|
-
resolveRootDirectory() {
|
|
4146
|
-
return this.rootDirectory ?? process.env.STORAGE_PATH ?? "storage";
|
|
4147
|
-
}
|
|
4148
|
-
resolvePath(path) {
|
|
4149
|
-
return join3(this.resolveRootDirectory(), path.replace(/^\/+/, ""));
|
|
4150
|
-
}
|
|
4151
|
-
async put(path, contents) {
|
|
4152
|
-
const absolutePath = this.resolvePath(path);
|
|
4153
|
-
await mkdir(dirname(absolutePath), { recursive: true });
|
|
4154
|
-
await writeFile(absolutePath, contents);
|
|
4155
|
-
return path;
|
|
4156
|
-
}
|
|
4157
|
-
async get(path) {
|
|
4158
|
-
try {
|
|
4159
|
-
return await readFile(this.resolvePath(path));
|
|
4160
|
-
} catch {
|
|
4161
|
-
return null;
|
|
4162
|
-
}
|
|
4163
|
-
}
|
|
4164
|
-
async delete(path) {
|
|
4165
|
-
try {
|
|
4166
|
-
await unlink(this.resolvePath(path));
|
|
4167
|
-
return true;
|
|
4168
|
-
} catch {
|
|
4169
|
-
return false;
|
|
4170
|
-
}
|
|
4171
|
-
}
|
|
4172
|
-
}
|
|
4173
|
-
|
|
4174
|
-
class S3StorageDriver {
|
|
4175
|
-
client;
|
|
4176
|
-
constructor(client) {
|
|
4177
|
-
this.client = client;
|
|
4178
|
-
}
|
|
4179
|
-
async put(path, contents) {
|
|
4180
|
-
await this.client.write(path.replace(/^\/+/, ""), contents);
|
|
4181
|
-
return path;
|
|
4182
|
-
}
|
|
4183
|
-
async get(path) {
|
|
4184
|
-
const normalizedPath = path.replace(/^\/+/, "");
|
|
4185
|
-
const file = this.client.file(normalizedPath);
|
|
4186
|
-
if (!await file.exists()) {
|
|
4187
|
-
return null;
|
|
4188
|
-
}
|
|
4189
|
-
return new Uint8Array(await file.arrayBuffer());
|
|
4190
|
-
}
|
|
4191
|
-
async delete(path) {
|
|
4192
|
-
try {
|
|
4193
|
-
await this.client.unlink(path.replace(/^\/+/, ""));
|
|
4194
|
-
return true;
|
|
4195
|
-
} catch {
|
|
4196
|
-
return false;
|
|
4197
|
-
}
|
|
4198
|
-
}
|
|
4199
|
-
}
|
|
4200
|
-
|
|
4201
|
-
class StorageManager {
|
|
4202
|
-
driver;
|
|
4203
|
-
constructor(driver) {
|
|
4204
|
-
this.driver = driver;
|
|
4205
|
-
}
|
|
4206
|
-
put(path, contents) {
|
|
4207
|
-
return this.driver.put(path, contents);
|
|
4208
|
-
}
|
|
4209
|
-
get(path) {
|
|
4210
|
-
return this.driver.get(path);
|
|
4211
|
-
}
|
|
4212
|
-
delete(path) {
|
|
4213
|
-
return this.driver.delete(path);
|
|
4214
|
-
}
|
|
4215
|
-
}
|
|
4216
|
-
function resolveS3Config() {
|
|
4217
|
-
const accessKeyId = process.env.AWS_ACCESS_KEY_ID?.trim();
|
|
4218
|
-
const secretAccessKey = process.env.AWS_SECRET_ACCESS_KEY?.trim();
|
|
4219
|
-
const bucket = process.env.AWS_BUCKET?.trim();
|
|
4220
|
-
if (!accessKeyId || !secretAccessKey || !bucket) {
|
|
4221
|
-
throw new Error('STORAGE_DRIVER="s3" requires AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, and AWS_BUCKET.');
|
|
4222
|
-
}
|
|
4223
|
-
return {
|
|
4224
|
-
accessKeyId,
|
|
4225
|
-
secretAccessKey,
|
|
4226
|
-
bucket,
|
|
4227
|
-
...process.env.AWS_REGION?.trim() ? { region: process.env.AWS_REGION.trim() } : {},
|
|
4228
|
-
...process.env.AWS_ENDPOINT?.trim() ? { endpoint: process.env.AWS_ENDPOINT.trim() } : {}
|
|
4229
|
-
};
|
|
4230
|
-
}
|
|
4231
|
-
function createS3Client(config = resolveS3Config()) {
|
|
4232
|
-
return new S3Client({
|
|
4233
|
-
accessKeyId: config.accessKeyId,
|
|
4234
|
-
secretAccessKey: config.secretAccessKey,
|
|
4235
|
-
bucket: config.bucket,
|
|
4236
|
-
...config.region ? { region: config.region } : {},
|
|
4237
|
-
...config.endpoint ? { endpoint: config.endpoint } : {}
|
|
4238
|
-
});
|
|
4239
|
-
}
|
|
4240
|
-
function createStorageDriver() {
|
|
4241
|
-
const driver = process.env.STORAGE_DRIVER ?? "local";
|
|
4242
|
-
if (driver === "s3") {
|
|
4243
|
-
return new S3StorageDriver(createS3Client());
|
|
4244
|
-
}
|
|
4245
|
-
return new LocalStorageDriver;
|
|
4246
|
-
}
|
|
4247
|
-
|
|
4248
|
-
// ../../src/bootstrap/providers/storage.ts
|
|
4249
|
-
var storageProvider = {
|
|
4250
|
-
name: "core.storage",
|
|
4251
|
-
register({ dependencies }) {
|
|
4252
|
-
dependencies.storage = new StorageManager(createStorageDriver());
|
|
1356
|
+
};
|
|
1357
|
+
var queue_default = queueProvider;
|
|
1358
|
+
|
|
1359
|
+
// ../../src/bootstrap/providers/storage.ts
|
|
1360
|
+
import { createStorageDriver, StorageManager } from "@getstrata/core/storage/storage";
|
|
1361
|
+
var storageProvider = {
|
|
1362
|
+
name: "core.storage",
|
|
1363
|
+
register({ dependencies }) {
|
|
1364
|
+
dependencies.storage = new StorageManager(createStorageDriver());
|
|
4253
1365
|
}
|
|
4254
1366
|
};
|
|
4255
1367
|
var storage_default = storageProvider;
|
|
4256
1368
|
|
|
4257
|
-
// ../../src/core/http/requestMetaContext.ts
|
|
4258
|
-
var requestMetaContext = createAsyncContextStore("@getstrata/requestMetaContext");
|
|
4259
|
-
function currentRequestMeta() {
|
|
4260
|
-
return requestMetaContext.getStore() ?? {
|
|
4261
|
-
ipAddress: null,
|
|
4262
|
-
userAgent: null
|
|
4263
|
-
};
|
|
4264
|
-
}
|
|
4265
|
-
|
|
4266
|
-
// ../../src/core/view/etaViewEngine.ts
|
|
4267
|
-
import { join as join4 } from "path";
|
|
4268
|
-
import { Eta } from "eta";
|
|
4269
|
-
var DEFAULT_VIEWS_DIRECTORY = join4(process.cwd(), "resources/views");
|
|
4270
|
-
var DEFAULT_LAYOUT = "layouts/app.eta";
|
|
4271
|
-
|
|
4272
|
-
class EtaViewEngine {
|
|
4273
|
-
eta;
|
|
4274
|
-
resolveLayoutData;
|
|
4275
|
-
constructor(viewsDirectory = DEFAULT_VIEWS_DIRECTORY, resolveLayoutData) {
|
|
4276
|
-
this.eta = new Eta({
|
|
4277
|
-
views: viewsDirectory,
|
|
4278
|
-
autoTrim: false
|
|
4279
|
-
});
|
|
4280
|
-
this.resolveLayoutData = resolveLayoutData;
|
|
4281
|
-
}
|
|
4282
|
-
async render(name, data = {}, options = {}) {
|
|
4283
|
-
const template = name.endsWith(".eta") ? name : `${name}.eta`;
|
|
4284
|
-
const layoutData = this.resolveLayoutData ? await this.resolveLayoutData() : {};
|
|
4285
|
-
const mergedData = { ...layoutData, ...data };
|
|
4286
|
-
const body = await this.eta.renderAsync(template, mergedData);
|
|
4287
|
-
const layout = options.layout ?? DEFAULT_LAYOUT;
|
|
4288
|
-
if (layout === false) {
|
|
4289
|
-
return body;
|
|
4290
|
-
}
|
|
4291
|
-
const layoutTemplate = layout.endsWith(".eta") ? layout : `${layout}.eta`;
|
|
4292
|
-
return await this.eta.renderAsync(layoutTemplate, {
|
|
4293
|
-
...mergedData,
|
|
4294
|
-
body
|
|
4295
|
-
});
|
|
4296
|
-
}
|
|
4297
|
-
}
|
|
4298
|
-
// ../../src/core/http/cookies.ts
|
|
4299
|
-
function readRequestCookie(request, name) {
|
|
4300
|
-
const cookies = request.cookies;
|
|
4301
|
-
if (cookies && typeof cookies.get === "function") {
|
|
4302
|
-
const value = cookies.get(name);
|
|
4303
|
-
if (value) {
|
|
4304
|
-
return value;
|
|
4305
|
-
}
|
|
4306
|
-
}
|
|
4307
|
-
const header = request.headers.get("cookie");
|
|
4308
|
-
if (!header) {
|
|
4309
|
-
return null;
|
|
4310
|
-
}
|
|
4311
|
-
for (const part of header.split(";")) {
|
|
4312
|
-
const idx = part.indexOf("=");
|
|
4313
|
-
if (idx === -1)
|
|
4314
|
-
continue;
|
|
4315
|
-
const cookieName = part.slice(0, idx).trim();
|
|
4316
|
-
if (cookieName !== name)
|
|
4317
|
-
continue;
|
|
4318
|
-
return decodeURIComponent(part.slice(idx + 1).trim());
|
|
4319
|
-
}
|
|
4320
|
-
return null;
|
|
4321
|
-
}
|
|
4322
|
-
|
|
4323
|
-
// ../../src/core/http/csrfToken.ts
|
|
4324
|
-
var CSRF_COOKIE = "workhub_csrf";
|
|
4325
|
-
var CSRF_TTL_MS = 60 * 60 * 1000;
|
|
4326
|
-
function resolveCsrfSecret() {
|
|
4327
|
-
return process.env.SESSION_SECRET?.trim() || process.env.OAUTH_STATE_SECRET?.trim() || process.env.ADMIN_API_TOKEN?.trim() || "workhub-dev-csrf-secret";
|
|
4328
|
-
}
|
|
4329
|
-
function csrfVerifyOptions() {
|
|
4330
|
-
return { secret: resolveCsrfSecret(), maxAge: CSRF_TTL_MS };
|
|
4331
|
-
}
|
|
4332
|
-
function createCsrfTokenCookie() {
|
|
4333
|
-
const token = Bun.CSRF.generate(resolveCsrfSecret(), { expiresIn: CSRF_TTL_MS });
|
|
4334
|
-
return {
|
|
4335
|
-
token,
|
|
4336
|
-
cookie: `${CSRF_COOKIE}=${encodeURIComponent(token)}; Path=/; SameSite=Lax; Max-Age=${Math.floor(CSRF_TTL_MS / 1000)}`
|
|
4337
|
-
};
|
|
4338
|
-
}
|
|
4339
|
-
function resolveCsrfToken(request) {
|
|
4340
|
-
const cookieValue = readRequestCookie(request, CSRF_COOKIE);
|
|
4341
|
-
if (cookieValue && Bun.CSRF.verify(cookieValue, csrfVerifyOptions())) {
|
|
4342
|
-
return { token: cookieValue };
|
|
4343
|
-
}
|
|
4344
|
-
return createCsrfTokenCookie();
|
|
4345
|
-
}
|
|
4346
|
-
function resolveCsrfTokenForRequest(request) {
|
|
4347
|
-
const metaToken = currentRequestMeta().csrfToken;
|
|
4348
|
-
if (metaToken) {
|
|
4349
|
-
return metaToken;
|
|
4350
|
-
}
|
|
4351
|
-
return resolveCsrfToken(request).token;
|
|
4352
|
-
}
|
|
4353
|
-
|
|
4354
|
-
// ../../src/core/http/flashSession.ts
|
|
4355
|
-
import { createHmac as createHmac3, timingSafeEqual as timingSafeEqual2 } from "crypto";
|
|
4356
|
-
var FLASH_COOKIE = "workhub_flash";
|
|
4357
|
-
var FLASH_TTL_MS = 60 * 1000;
|
|
4358
|
-
function resolveFlashSecret() {
|
|
4359
|
-
return process.env.SESSION_SECRET?.trim() || process.env.OAUTH_STATE_SECRET?.trim() || "workhub-dev-flash-secret";
|
|
4360
|
-
}
|
|
4361
|
-
function signFlashPayload(payload, issuedAt) {
|
|
4362
|
-
const signature = createHmac3("sha256", resolveFlashSecret()).update(`${payload}.${issuedAt}`).digest("hex");
|
|
4363
|
-
return `${payload}.${issuedAt}.${signature}`;
|
|
4364
|
-
}
|
|
4365
|
-
function readFlashCookie(request) {
|
|
4366
|
-
const cookieHeader = request.headers.get("cookie");
|
|
4367
|
-
if (!cookieHeader) {
|
|
4368
|
-
return null;
|
|
4369
|
-
}
|
|
4370
|
-
for (const part of cookieHeader.split(";")) {
|
|
4371
|
-
const [name, ...rest] = part.trim().split("=");
|
|
4372
|
-
if (name === FLASH_COOKIE) {
|
|
4373
|
-
return decodeURIComponent(rest.join("="));
|
|
4374
|
-
}
|
|
4375
|
-
}
|
|
4376
|
-
return null;
|
|
4377
|
-
}
|
|
4378
|
-
function parseFlashCookie(cookieValue) {
|
|
4379
|
-
const parts = cookieValue.split(".");
|
|
4380
|
-
if (parts.length < 3) {
|
|
4381
|
-
return null;
|
|
4382
|
-
}
|
|
4383
|
-
const signature = parts.pop();
|
|
4384
|
-
const issuedAtRaw = parts.pop();
|
|
4385
|
-
const payload = parts.join(".");
|
|
4386
|
-
if (!signature || !issuedAtRaw || !payload) {
|
|
4387
|
-
return null;
|
|
4388
|
-
}
|
|
4389
|
-
const issuedAt = Number.parseInt(issuedAtRaw, 10);
|
|
4390
|
-
if (!Number.isFinite(issuedAt) || Date.now() - issuedAt > FLASH_TTL_MS) {
|
|
4391
|
-
return null;
|
|
4392
|
-
}
|
|
4393
|
-
const expectedSignature = signFlashPayload(payload, issuedAt).split(".").pop();
|
|
4394
|
-
if (!expectedSignature) {
|
|
4395
|
-
return null;
|
|
4396
|
-
}
|
|
4397
|
-
const expectedBuffer = Buffer.from(expectedSignature);
|
|
4398
|
-
const actualBuffer = Buffer.from(signature);
|
|
4399
|
-
if (expectedBuffer.length !== actualBuffer.length) {
|
|
4400
|
-
return null;
|
|
4401
|
-
}
|
|
4402
|
-
if (!timingSafeEqual2(expectedBuffer, actualBuffer)) {
|
|
4403
|
-
return null;
|
|
4404
|
-
}
|
|
4405
|
-
try {
|
|
4406
|
-
const parsed = JSON.parse(Buffer.from(payload, "base64url").toString("utf8"));
|
|
4407
|
-
if (!parsed?.message || typeof parsed.message !== "string") {
|
|
4408
|
-
return null;
|
|
4409
|
-
}
|
|
4410
|
-
if (parsed.level !== "success" && parsed.level !== "error" && parsed.level !== "info") {
|
|
4411
|
-
return null;
|
|
4412
|
-
}
|
|
4413
|
-
return parsed;
|
|
4414
|
-
} catch {
|
|
4415
|
-
return null;
|
|
4416
|
-
}
|
|
4417
|
-
}
|
|
4418
|
-
function pullFlash(request) {
|
|
4419
|
-
const cookieValue = readFlashCookie(request);
|
|
4420
|
-
if (!cookieValue) {
|
|
4421
|
-
return null;
|
|
4422
|
-
}
|
|
4423
|
-
return parseFlashCookie(cookieValue);
|
|
4424
|
-
}
|
|
4425
|
-
|
|
4426
|
-
// ../../src/core/view/webLayoutData.ts
|
|
4427
|
-
async function resolveWebLayoutData(container, request) {
|
|
4428
|
-
const csrfToken = request ? resolveCsrfTokenForRequest(request) : "";
|
|
4429
|
-
const flash = request ? currentRequestMeta().flash ?? pullFlash(request) : null;
|
|
4430
|
-
const authUser = currentAuthUser();
|
|
4431
|
-
if (!authUser) {
|
|
4432
|
-
return { authUser: null, csrfToken, flash };
|
|
4433
|
-
}
|
|
4434
|
-
const userId = Number(authUser.id);
|
|
4435
|
-
if (!Number.isInteger(userId) || userId <= 0) {
|
|
4436
|
-
return { authUser: null, csrfToken, flash };
|
|
4437
|
-
}
|
|
4438
|
-
if (!container.has(tokenServiceToken)) {
|
|
4439
|
-
return {
|
|
4440
|
-
authUser: {
|
|
4441
|
-
id: userId,
|
|
4442
|
-
email: "",
|
|
4443
|
-
role: authUser.role ?? "member"
|
|
4444
|
-
},
|
|
4445
|
-
csrfToken,
|
|
4446
|
-
flash
|
|
4447
|
-
};
|
|
4448
|
-
}
|
|
4449
|
-
const tokenService = container.resolve(tokenServiceToken);
|
|
4450
|
-
try {
|
|
4451
|
-
const user = await tokenService.findByIdOrThrow(userId);
|
|
4452
|
-
return {
|
|
4453
|
-
authUser: {
|
|
4454
|
-
id: userId,
|
|
4455
|
-
email: user.email ?? "",
|
|
4456
|
-
role: authUser.role ?? user.role ?? "member"
|
|
4457
|
-
},
|
|
4458
|
-
csrfToken,
|
|
4459
|
-
flash
|
|
4460
|
-
};
|
|
4461
|
-
} catch {
|
|
4462
|
-
return { authUser: null, csrfToken, flash };
|
|
4463
|
-
}
|
|
4464
|
-
}
|
|
4465
1369
|
// ../../src/bootstrap/providers/view.ts
|
|
1370
|
+
import { currentRequestMeta } from "@getstrata/core/http/requestMetaContext";
|
|
1371
|
+
import { DEFAULT_VIEWS_DIRECTORY, EtaViewEngine, resolveWebLayoutData } from "@getstrata/core/view";
|
|
4466
1372
|
var CORE_VIEW_TOKEN = "core.view";
|
|
4467
1373
|
var VIEW_DIRECTORY_CONFIG_KEY = "view.directory";
|
|
4468
1374
|
var viewProvider = {
|
|
@@ -4582,8 +1488,8 @@ function createAppContext() {
|
|
|
4582
1488
|
return appContext;
|
|
4583
1489
|
}
|
|
4584
1490
|
// ../../src/bootstrap/createWebRoutes.ts
|
|
4585
|
-
import { join as
|
|
4586
|
-
import { htmlResponse
|
|
1491
|
+
import { join as join3 } from "path";
|
|
1492
|
+
import { htmlResponse } from "@getstrata/core/view";
|
|
4587
1493
|
function registerRoute(method, path, middleware) {
|
|
4588
1494
|
routeRegistry.register({ method, path, middleware });
|
|
4589
1495
|
}
|
|
@@ -4599,9 +1505,9 @@ function createWebRoutes(dependencies) {
|
|
|
4599
1505
|
registerRoute("GET", "/assets/*", ["global", "web"]);
|
|
4600
1506
|
const pathname = new URL(request.url).pathname;
|
|
4601
1507
|
const relativePath = pathname.replace(/^\//, "");
|
|
4602
|
-
const file = Bun.file(
|
|
1508
|
+
const file = Bun.file(join3(process.cwd(), "public", relativePath));
|
|
4603
1509
|
if (!await file.exists()) {
|
|
4604
|
-
return
|
|
1510
|
+
return htmlResponse("Not Found", { status: 404 });
|
|
4605
1511
|
}
|
|
4606
1512
|
return new Response(file);
|
|
4607
1513
|
};
|
|
@@ -4621,178 +1527,17 @@ function mergeWebRoutes(dependencies, routes) {
|
|
|
4621
1527
|
function createAppDependencies() {
|
|
4622
1528
|
return createAppContext().dependencies;
|
|
4623
1529
|
}
|
|
4624
|
-
// ../../src/
|
|
4625
|
-
|
|
4626
|
-
|
|
4627
|
-
|
|
4628
|
-
|
|
4629
|
-
// ../../src/core/http/etag.ts
|
|
4630
|
-
function isEtagEnabled() {
|
|
4631
|
-
return (process.env.FEATURE_ETAG ?? "true") !== "false";
|
|
4632
|
-
}
|
|
4633
|
-
function formatWeakEtag(digest) {
|
|
4634
|
-
return `W/"${digest}"`;
|
|
4635
|
-
}
|
|
4636
|
-
function etagFromResource(resource) {
|
|
4637
|
-
const version = resource.updated_at ?? resource.created_at ?? "";
|
|
4638
|
-
const versionText = version instanceof Date ? version.toISOString() : version ? String(version) : "0";
|
|
4639
|
-
const digest = nonCryptographicDigest(`${String(resource.id ?? "0")}:${versionText}`).slice(0, 32);
|
|
4640
|
-
return formatWeakEtag(digest);
|
|
4641
|
-
}
|
|
4642
|
-
function normalizeEtag(value) {
|
|
4643
|
-
return value.trim();
|
|
4644
|
-
}
|
|
4645
|
-
function etagValuesMatch(left, right) {
|
|
4646
|
-
return normalizeEtag(left) === normalizeEtag(right);
|
|
4647
|
-
}
|
|
4648
|
-
function parseEtagList(header) {
|
|
4649
|
-
if (!header) {
|
|
4650
|
-
return [];
|
|
4651
|
-
}
|
|
4652
|
-
return header.split(",").map((value) => normalizeEtag(value)).filter(Boolean);
|
|
4653
|
-
}
|
|
4654
|
-
function ifNoneMatchSatisfied(request, etag) {
|
|
4655
|
-
const header = request.headers.get("if-none-match");
|
|
4656
|
-
if (!header) {
|
|
4657
|
-
return false;
|
|
4658
|
-
}
|
|
4659
|
-
if (header.trim() === "*") {
|
|
4660
|
-
return true;
|
|
4661
|
-
}
|
|
4662
|
-
return parseEtagList(header).some((candidate) => etagValuesMatch(candidate, etag));
|
|
4663
|
-
}
|
|
4664
|
-
function ifMatchSatisfied(request, etag) {
|
|
4665
|
-
const header = request.headers.get("if-match");
|
|
4666
|
-
if (!header) {
|
|
4667
|
-
return false;
|
|
4668
|
-
}
|
|
4669
|
-
if (header.trim() === "*") {
|
|
4670
|
-
return true;
|
|
4671
|
-
}
|
|
4672
|
-
return parseEtagList(header).some((candidate) => etagValuesMatch(candidate, etag));
|
|
4673
|
-
}
|
|
4674
|
-
function assertIfMatch(request, etag, options = {}) {
|
|
4675
|
-
const header = request.headers.get("if-match");
|
|
4676
|
-
if (!header) {
|
|
4677
|
-
if (options.required) {
|
|
4678
|
-
throw new PreconditionFailedError("If-Match header is required.");
|
|
4679
|
-
}
|
|
4680
|
-
return;
|
|
4681
|
-
}
|
|
4682
|
-
if (!ifMatchSatisfied(request, etag)) {
|
|
4683
|
-
throw new PreconditionFailedError("Resource ETag does not match If-Match.");
|
|
4684
|
-
}
|
|
4685
|
-
}
|
|
4686
|
-
function applyEtagHeaders(headers, etag) {
|
|
4687
|
-
const next = new Headers(headers);
|
|
4688
|
-
next.set("ETag", etag);
|
|
4689
|
-
next.set("Cache-Control", "private, must-revalidate");
|
|
4690
|
-
next.append("Vary", "Authorization");
|
|
4691
|
-
next.append("Vary", "X-Tenant-Id");
|
|
4692
|
-
return next;
|
|
4693
|
-
}
|
|
4694
|
-
function notModifiedResponse(etag) {
|
|
4695
|
-
return new Response(null, {
|
|
4696
|
-
status: 304,
|
|
4697
|
-
headers: applyEtagHeaders(new Headers, etag)
|
|
4698
|
-
});
|
|
4699
|
-
}
|
|
4700
|
-
function applyConditionalGet(request, response, etag) {
|
|
4701
|
-
if (!isEtagEnabled()) {
|
|
4702
|
-
return response;
|
|
4703
|
-
}
|
|
4704
|
-
if (ifNoneMatchSatisfied(request, etag)) {
|
|
4705
|
-
return notModifiedResponse(etag);
|
|
4706
|
-
}
|
|
4707
|
-
const headers = applyEtagHeaders(new Headers(response.headers), etag);
|
|
4708
|
-
return new Response(response.body, {
|
|
4709
|
-
status: response.status,
|
|
4710
|
-
statusText: response.statusText,
|
|
4711
|
-
headers
|
|
4712
|
-
});
|
|
4713
|
-
}
|
|
4714
|
-
|
|
4715
|
-
// ../../src/core/tenant/tenantContext.ts
|
|
4716
|
-
var tenantContext = createAsyncContextStore("@getstrata/tenantContext");
|
|
4717
|
-
|
|
4718
|
-
// ../../src/core/http/validation.ts
|
|
4719
|
-
function parsePositiveIntParam(value, name = "id") {
|
|
4720
|
-
const parsed = Number.parseInt(value, 10);
|
|
4721
|
-
if (!Number.isInteger(parsed) || parsed <= 0) {
|
|
4722
|
-
throw new BadRequestError(`Invalid ${name}. Expected a positive integer.`);
|
|
4723
|
-
}
|
|
4724
|
-
return parsed;
|
|
4725
|
-
}
|
|
4726
|
-
|
|
4727
|
-
// ../../src/core/http/securedRouteModelBinding.ts
|
|
4728
|
-
function isMutatingPolicyAction(action) {
|
|
4729
|
-
return action === "update" || action === "delete";
|
|
4730
|
-
}
|
|
4731
|
-
function securedBindRouteModel(param, resolver, authorization, handler) {
|
|
4732
|
-
return async (request) => {
|
|
4733
|
-
const id = parsePositiveIntParam(String(request.params[param]), String(param));
|
|
4734
|
-
const model = await resolver(id, request);
|
|
4735
|
-
const gate = resolveApplicationPolicyGate2();
|
|
4736
|
-
const auth = resolveApplicationAuth2();
|
|
4737
|
-
const user = currentAuthUser() ?? await auth.resolve(request);
|
|
4738
|
-
gate.authorize(authorization.resource, authorization.action, user, model);
|
|
4739
|
-
if (isEtagEnabled() && isMutatingPolicyAction(authorization.action)) {
|
|
4740
|
-
assertIfMatch(request, etagFromResource(model), {
|
|
4741
|
-
required: authorization.requireIfMatch ?? true
|
|
4742
|
-
});
|
|
4743
|
-
}
|
|
4744
|
-
const response = await handler(request, model);
|
|
4745
|
-
if (isEtagEnabled() && authorization.action === "view") {
|
|
4746
|
-
return applyConditionalGet(request, response, etagFromResource(model));
|
|
4747
|
-
}
|
|
4748
|
-
return response;
|
|
4749
|
-
};
|
|
4750
|
-
}
|
|
4751
|
-
function securedBindRouteModelByKey(param, resolver, authorization, handler) {
|
|
4752
|
-
return async (request) => {
|
|
4753
|
-
const key = String(request.params[param] ?? "").trim();
|
|
4754
|
-
if (!key) {
|
|
4755
|
-
throw new BadRequestError(`Missing route parameter "${String(param)}".`);
|
|
4756
|
-
}
|
|
4757
|
-
const model = await resolver(key, request);
|
|
4758
|
-
const gate = resolveApplicationPolicyGate2();
|
|
4759
|
-
const auth = resolveApplicationAuth2();
|
|
4760
|
-
const user = currentAuthUser() ?? await auth.resolve(request);
|
|
4761
|
-
gate.authorize(authorization.resource, authorization.action, user, model);
|
|
4762
|
-
if (isEtagEnabled() && isMutatingPolicyAction(authorization.action)) {
|
|
4763
|
-
assertIfMatch(request, etagFromResource(model), {
|
|
4764
|
-
required: authorization.requireIfMatch ?? true
|
|
4765
|
-
});
|
|
4766
|
-
}
|
|
4767
|
-
const response = await handler(request, model);
|
|
4768
|
-
if (isEtagEnabled() && authorization.action === "view") {
|
|
4769
|
-
return applyConditionalGet(request, response, etagFromResource(model));
|
|
4770
|
-
}
|
|
4771
|
-
return response;
|
|
4772
|
-
};
|
|
4773
|
-
}
|
|
1530
|
+
// ../../src/bootstrap/http/securedRouteModelBinding.ts
|
|
1531
|
+
import {
|
|
1532
|
+
securedBindRouteModel,
|
|
1533
|
+
securedBindRouteModelByKey
|
|
1534
|
+
} from "@getstrata/core/http/securedRouteModelBinding";
|
|
4774
1535
|
// ../../src/bootstrap/membershipService.ts
|
|
4775
1536
|
import { resolveMembershipService } from "@getstrata/core/auth/membershipService";
|
|
4776
|
-
// ../../src/core/http/csrfProtection.ts
|
|
4777
|
-
var DEFAULT_CSRF_TTL_MS = 60 * 60 * 1000;
|
|
4778
|
-
function createCsrfProtection(secret, options = {}) {
|
|
4779
|
-
const expiresIn = options.expiresIn ?? DEFAULT_CSRF_TTL_MS;
|
|
4780
|
-
const maxAge = options.maxAge ?? expiresIn;
|
|
4781
|
-
return {
|
|
4782
|
-
generate(_sessionKey) {
|
|
4783
|
-
return Bun.CSRF.generate(secret, { expiresIn });
|
|
4784
|
-
},
|
|
4785
|
-
verify(token, _sessionKey) {
|
|
4786
|
-
if (!token) {
|
|
4787
|
-
return false;
|
|
4788
|
-
}
|
|
4789
|
-
return Bun.CSRF.verify(token, { secret, maxAge });
|
|
4790
|
-
},
|
|
4791
|
-
secret
|
|
4792
|
-
};
|
|
4793
|
-
}
|
|
4794
|
-
|
|
4795
1537
|
// ../../src/bootstrap/web/forms.ts
|
|
1538
|
+
import {
|
|
1539
|
+
createCsrfProtection
|
|
1540
|
+
} from "@getstrata/core/http/csrfProtection";
|
|
4796
1541
|
async function parseFormBody(request) {
|
|
4797
1542
|
const contentType = request.headers.get("content-type") ?? "";
|
|
4798
1543
|
const fields = {};
|
|
@@ -4920,6 +1665,8 @@ function createWebServer(options) {
|
|
|
4920
1665
|
}
|
|
4921
1666
|
// ../../src/bootstrap/web/session.ts
|
|
4922
1667
|
import { createHash, randomBytes } from "crypto";
|
|
1668
|
+
import { readRequestCookie } from "@getstrata/core/http/cookies";
|
|
1669
|
+
|
|
4923
1670
|
class CookieSessionStore {
|
|
4924
1671
|
sql;
|
|
4925
1672
|
secret;
|