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