@getstrata/core 0.5.13 → 0.5.15
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/README.md +16 -6
- package/dist/bootstrap/contracts.d.ts +2 -0
- package/dist/bootstrap/httpKernel.d.ts +1 -2
- package/dist/core/admin/registry.d.ts +1 -0
- package/dist/core/auth/membershipService.d.ts +5 -1
- 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/jobs/dispatchWebhookJob.d.ts +0 -1
- package/dist/core/security/safeFetch.d.ts +2 -0
- package/dist/core/security/safeUrl.d.ts +16 -1
- package/dist/core/storage/storage.d.ts +6 -3
- package/dist/core/tenant/tenantDatabaseScope.d.ts +2 -1
- package/dist/db/connection/index.d.ts +1 -1
- package/dist/entries/auth/accessControl.js +1 -113
- package/dist/entries/auth/authContext.js +1 -15
- package/dist/entries/auth/guard.js +1 -3044
- package/dist/entries/auth/membershipContext.js +1 -276
- package/dist/entries/auth/membershipScope.js +1 -390
- package/dist/entries/auth/membershipService.js +1 -480
- package/dist/entries/auth/policy.js +1 -134
- package/dist/entries/database.js +1 -2398
- package/dist/entries/http/csrfToken.js +0 -6
- package/dist/entries/http/middleware.js +1 -68
- package/dist/entries/http/requestMetaContext.js +1 -18
- package/dist/entries/http/webErrorResponse.js +94 -563
- package/dist/entries/http/webFormRequest.js +0 -131
- package/dist/entries/http.js +1 -4091
- package/dist/entries/jobs/dispatchWebhookJob.js +109 -102
- package/dist/entries/queue/createAppQueue.js +111 -631
- package/dist/entries/queue/jobRunner.js +0 -3
- package/dist/entries/queue/publicQueue.js +45 -546
- package/dist/entries/queue/queueMetrics.js +111 -631
- package/dist/entries/security/safeUrl.js +29 -0
- package/dist/entries/security/securityEvents.js +1 -41
- package/dist/entries/storage/storage.js +14 -4
- package/dist/entries/tenant/tenantContext.js +1 -30
- package/dist/entries/tenant/tenantMiddleware.js +1 -312
- package/dist/entries/tracing/traceContext.js +1 -15
- package/dist/entries/view.js +94 -563
- package/dist/framework/public-api.d.ts +36 -4
- package/dist/index.js +2270 -1666
- package/dist/modules/user/repository.d.ts +1 -0
- package/package.json +6 -5
|
@@ -1,3044 +1 @@
|
|
|
1
|
-
|
|
2
|
-
// ../../src/domain/abilities.ts
|
|
3
|
-
var MEMBER_ABILITIES = [
|
|
4
|
-
"organizations:read",
|
|
5
|
-
"projects:read",
|
|
6
|
-
"projects:create",
|
|
7
|
-
"tasks:read",
|
|
8
|
-
"tasks:create",
|
|
9
|
-
"comments:read",
|
|
10
|
-
"comments:create",
|
|
11
|
-
"attachments:read",
|
|
12
|
-
"attachments:create",
|
|
13
|
-
"auth:tokens:read",
|
|
14
|
-
"auth:tokens:write"
|
|
15
|
-
];
|
|
16
|
-
var ADMIN_ABILITIES = [
|
|
17
|
-
...MEMBER_ABILITIES,
|
|
18
|
-
"organizations:create",
|
|
19
|
-
"organizations:update",
|
|
20
|
-
"organizations:delete",
|
|
21
|
-
"projects:update",
|
|
22
|
-
"projects:delete",
|
|
23
|
-
"tasks:update",
|
|
24
|
-
"tasks:delete",
|
|
25
|
-
"comments:update",
|
|
26
|
-
"comments:delete",
|
|
27
|
-
"attachments:delete",
|
|
28
|
-
"webhooks:read",
|
|
29
|
-
"webhooks:write",
|
|
30
|
-
"audit:read"
|
|
31
|
-
];
|
|
32
|
-
var PLATFORM_ADMIN_ABILITIES = ["*"];
|
|
33
|
-
function resolveAbilitiesForRole(role) {
|
|
34
|
-
if (role === "admin") {
|
|
35
|
-
return [...PLATFORM_ADMIN_ABILITIES];
|
|
36
|
-
}
|
|
37
|
-
return [...MEMBER_ABILITIES];
|
|
38
|
-
}
|
|
39
|
-
|
|
40
|
-
// ../../src/bootstrap/config.ts
|
|
41
|
-
var CORE_QUEUE_TOKEN = "core.queue";
|
|
42
|
-
var CORE_POLICY_GATE_TOKEN = "core.policyGate";
|
|
43
|
-
var CORE_AUTH_TOKEN = "core.auth";
|
|
44
|
-
var CORE_TOKEN_SERVICE_TOKEN = "core.tokenService";
|
|
45
|
-
var DEFAULT_QUEUE_DRIVER = "sync";
|
|
46
|
-
|
|
47
|
-
// ../../src/core/auth/oauth/oidcProvider.ts
|
|
48
|
-
class OidcProvider {
|
|
49
|
-
options;
|
|
50
|
-
name;
|
|
51
|
-
constructor(options) {
|
|
52
|
-
this.options = options;
|
|
53
|
-
this.name = options.name;
|
|
54
|
-
}
|
|
55
|
-
getAuthorizationUrl(state) {
|
|
56
|
-
const params = new URLSearchParams({
|
|
57
|
-
client_id: this.options.clientId,
|
|
58
|
-
redirect_uri: this.options.redirectUri,
|
|
59
|
-
response_type: "code",
|
|
60
|
-
scope: (this.options.scopes ?? ["openid", "email", "profile"]).join(" "),
|
|
61
|
-
state
|
|
62
|
-
});
|
|
63
|
-
return `${this.options.issuer.replace(/\/$/, "")}/authorize?${params.toString()}`;
|
|
64
|
-
}
|
|
65
|
-
async exchangeCode(code) {
|
|
66
|
-
const tokenResponse = await fetch(`${this.options.issuer.replace(/\/$/, "")}/token`, {
|
|
67
|
-
method: "POST",
|
|
68
|
-
headers: { "content-type": "application/x-www-form-urlencoded" },
|
|
69
|
-
body: new URLSearchParams({
|
|
70
|
-
grant_type: "authorization_code",
|
|
71
|
-
code,
|
|
72
|
-
redirect_uri: this.options.redirectUri,
|
|
73
|
-
client_id: this.options.clientId,
|
|
74
|
-
client_secret: this.options.clientSecret
|
|
75
|
-
})
|
|
76
|
-
});
|
|
77
|
-
const tokenBody = await tokenResponse.json();
|
|
78
|
-
if (!tokenBody.access_token) {
|
|
79
|
-
throw new Error("OIDC token exchange failed.");
|
|
80
|
-
}
|
|
81
|
-
const profileResponse = await fetch(`${this.options.issuer.replace(/\/$/, "")}/userinfo`, {
|
|
82
|
-
headers: { authorization: `Bearer ${tokenBody.access_token}` }
|
|
83
|
-
});
|
|
84
|
-
const profile = await profileResponse.json();
|
|
85
|
-
return {
|
|
86
|
-
providerUserId: profile.sub,
|
|
87
|
-
email: profile.email ?? `${profile.sub}@oidc.local`,
|
|
88
|
-
name: profile.name ?? profile.sub
|
|
89
|
-
};
|
|
90
|
-
}
|
|
91
|
-
}
|
|
92
|
-
|
|
93
|
-
// ../../src/core/auth/oauth/providers.ts
|
|
94
|
-
class GitHubOAuthProvider {
|
|
95
|
-
options;
|
|
96
|
-
name = "github";
|
|
97
|
-
constructor(options) {
|
|
98
|
-
this.options = options;
|
|
99
|
-
}
|
|
100
|
-
getAuthorizationUrl(state) {
|
|
101
|
-
const params = new URLSearchParams({
|
|
102
|
-
client_id: this.options.clientId,
|
|
103
|
-
redirect_uri: this.options.redirectUri,
|
|
104
|
-
scope: "read:user user:email",
|
|
105
|
-
state
|
|
106
|
-
});
|
|
107
|
-
return `https://github.com/login/oauth/authorize?${params.toString()}`;
|
|
108
|
-
}
|
|
109
|
-
async exchangeCode(code) {
|
|
110
|
-
const tokenResponse = await fetch("https://github.com/login/oauth/access_token", {
|
|
111
|
-
method: "POST",
|
|
112
|
-
headers: {
|
|
113
|
-
accept: "application/json",
|
|
114
|
-
"content-type": "application/json"
|
|
115
|
-
},
|
|
116
|
-
body: JSON.stringify({
|
|
117
|
-
client_id: this.options.clientId,
|
|
118
|
-
client_secret: this.options.clientSecret,
|
|
119
|
-
code,
|
|
120
|
-
redirect_uri: this.options.redirectUri
|
|
121
|
-
})
|
|
122
|
-
});
|
|
123
|
-
const tokenBody = await tokenResponse.json();
|
|
124
|
-
if (!tokenBody.access_token) {
|
|
125
|
-
throw new Error("GitHub OAuth token exchange failed.");
|
|
126
|
-
}
|
|
127
|
-
const profileResponse = await fetch("https://api.github.com/user", {
|
|
128
|
-
headers: {
|
|
129
|
-
authorization: `Bearer ${tokenBody.access_token}`,
|
|
130
|
-
accept: "application/json",
|
|
131
|
-
"user-agent": "workhub"
|
|
132
|
-
}
|
|
133
|
-
});
|
|
134
|
-
const profile = await profileResponse.json();
|
|
135
|
-
return {
|
|
136
|
-
providerUserId: String(profile.id),
|
|
137
|
-
email: profile.email ?? `${profile.login}@users.noreply.github.com`,
|
|
138
|
-
name: profile.name ?? profile.login
|
|
139
|
-
};
|
|
140
|
-
}
|
|
141
|
-
}
|
|
142
|
-
|
|
143
|
-
class MockOAuthProvider {
|
|
144
|
-
profile;
|
|
145
|
-
name = "mock";
|
|
146
|
-
constructor(profile) {
|
|
147
|
-
this.profile = profile;
|
|
148
|
-
}
|
|
149
|
-
getAuthorizationUrl(state) {
|
|
150
|
-
return `https://mock.oauth/authorize?state=${encodeURIComponent(state)}`;
|
|
151
|
-
}
|
|
152
|
-
async exchangeCode(code) {
|
|
153
|
-
if (code !== "valid-code") {
|
|
154
|
-
throw new Error("Invalid OAuth code.");
|
|
155
|
-
}
|
|
156
|
-
return this.profile;
|
|
157
|
-
}
|
|
158
|
-
}
|
|
159
|
-
|
|
160
|
-
// ../../src/core/auth/oauth/samlProvider.ts
|
|
161
|
-
class SamlProvider {
|
|
162
|
-
loginUrl;
|
|
163
|
-
name = "saml";
|
|
164
|
-
constructor(loginUrl) {
|
|
165
|
-
this.loginUrl = loginUrl;
|
|
166
|
-
}
|
|
167
|
-
getAuthorizationUrl(state) {
|
|
168
|
-
return `${this.loginUrl}?state=${encodeURIComponent(state)}`;
|
|
169
|
-
}
|
|
170
|
-
async exchangeCode(code) {
|
|
171
|
-
if (!code.startsWith("saml:")) {
|
|
172
|
-
throw new Error("Invalid SAML assertion reference.");
|
|
173
|
-
}
|
|
174
|
-
const [, email, name] = code.split(":");
|
|
175
|
-
return {
|
|
176
|
-
providerUserId: email ?? "saml-user",
|
|
177
|
-
email: email ?? "saml-user@workhub.test",
|
|
178
|
-
name: name ?? "SAML User"
|
|
179
|
-
};
|
|
180
|
-
}
|
|
181
|
-
}
|
|
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/core/events/eventBus.ts
|
|
205
|
-
class EventBus {
|
|
206
|
-
constructor() {}
|
|
207
|
-
listeners = new Map;
|
|
208
|
-
listen(event, listener) {
|
|
209
|
-
const handlers = this.listeners.get(event) ?? new Set;
|
|
210
|
-
handlers.add(listener);
|
|
211
|
-
this.listeners.set(event, handlers);
|
|
212
|
-
return () => {
|
|
213
|
-
handlers.delete(listener);
|
|
214
|
-
if (handlers.size === 0) {
|
|
215
|
-
this.listeners.delete(event);
|
|
216
|
-
}
|
|
217
|
-
};
|
|
218
|
-
}
|
|
219
|
-
async dispatch(event, payload) {
|
|
220
|
-
const handlers = this.listeners.get(event);
|
|
221
|
-
if (!handlers || handlers.size === 0) {
|
|
222
|
-
return;
|
|
223
|
-
}
|
|
224
|
-
for (const handler of handlers) {
|
|
225
|
-
await handler(payload);
|
|
226
|
-
}
|
|
227
|
-
}
|
|
228
|
-
}
|
|
229
|
-
var eventBus = new EventBus;
|
|
230
|
-
|
|
231
|
-
// ../../src/core/events/index.ts
|
|
232
|
-
function modelEventName(tableName, action) {
|
|
233
|
-
return `${tableName}.${action}`;
|
|
234
|
-
}
|
|
235
|
-
|
|
236
|
-
// ../../src/core/pagination/index.ts
|
|
237
|
-
function buildPaginationMeta(input) {
|
|
238
|
-
const lastPage = Math.max(1, Math.ceil(input.total / input.perPage));
|
|
239
|
-
return {
|
|
240
|
-
page: input.page,
|
|
241
|
-
per_page: input.perPage,
|
|
242
|
-
total: input.total,
|
|
243
|
-
last_page: lastPage
|
|
244
|
-
};
|
|
245
|
-
}
|
|
246
|
-
|
|
247
|
-
// ../../src/core/errors/http.ts
|
|
248
|
-
class HttpError extends Error {
|
|
249
|
-
status;
|
|
250
|
-
details;
|
|
251
|
-
constructor(status, message, details) {
|
|
252
|
-
super(message);
|
|
253
|
-
this.name = new.target.name;
|
|
254
|
-
this.status = status;
|
|
255
|
-
this.details = details;
|
|
256
|
-
}
|
|
257
|
-
}
|
|
258
|
-
|
|
259
|
-
class BadRequestError extends HttpError {
|
|
260
|
-
constructor(message = "Bad Request", details) {
|
|
261
|
-
super(400, message, details);
|
|
262
|
-
}
|
|
263
|
-
}
|
|
264
|
-
|
|
265
|
-
class NotFoundError extends HttpError {
|
|
266
|
-
constructor(message = "Not Found", details) {
|
|
267
|
-
super(404, message, details);
|
|
268
|
-
}
|
|
269
|
-
}
|
|
270
|
-
|
|
271
|
-
class ConflictError extends HttpError {
|
|
272
|
-
constructor(message = "Conflict", details) {
|
|
273
|
-
super(409, message, details);
|
|
274
|
-
}
|
|
275
|
-
}
|
|
276
|
-
|
|
277
|
-
class UnprocessableEntityError extends HttpError {
|
|
278
|
-
constructor(message = "Unprocessable Entity", details) {
|
|
279
|
-
super(422, message, details);
|
|
280
|
-
}
|
|
281
|
-
}
|
|
282
|
-
|
|
283
|
-
class ValidationError extends HttpError {
|
|
284
|
-
constructor(message = "Validation failed", details) {
|
|
285
|
-
super(422, message, details);
|
|
286
|
-
}
|
|
287
|
-
}
|
|
288
|
-
|
|
289
|
-
class ForbiddenError extends HttpError {
|
|
290
|
-
constructor(message = "Forbidden", details) {
|
|
291
|
-
super(403, message, details);
|
|
292
|
-
}
|
|
293
|
-
}
|
|
294
|
-
|
|
295
|
-
class UnauthorizedError extends HttpError {
|
|
296
|
-
constructor(message = "Unauthorized", details) {
|
|
297
|
-
super(401, message, details);
|
|
298
|
-
}
|
|
299
|
-
}
|
|
300
|
-
|
|
301
|
-
class PayloadTooLargeError extends HttpError {
|
|
302
|
-
constructor(message = "Payload Too Large", details) {
|
|
303
|
-
super(413, message, details);
|
|
304
|
-
}
|
|
305
|
-
}
|
|
306
|
-
|
|
307
|
-
class PreconditionFailedError extends HttpError {
|
|
308
|
-
constructor(message = "Precondition Failed", details) {
|
|
309
|
-
super(412, message, details);
|
|
310
|
-
}
|
|
311
|
-
}
|
|
312
|
-
|
|
313
|
-
// ../../src/core/database/errors.ts
|
|
314
|
-
function isPostgresError(error) {
|
|
315
|
-
return typeof error === "object" && error !== null && (("errno" in error) || ("code" in error));
|
|
316
|
-
}
|
|
317
|
-
function getPostgresSqlState(error) {
|
|
318
|
-
if (typeof error.errno === "string" && /^\d{5}$/.test(error.errno)) {
|
|
319
|
-
return error.errno;
|
|
320
|
-
}
|
|
321
|
-
if (typeof error.errno === "number") {
|
|
322
|
-
return String(error.errno).padStart(5, "0");
|
|
323
|
-
}
|
|
324
|
-
if (typeof error.code === "string" && /^\d{5}$/.test(error.code)) {
|
|
325
|
-
return error.code;
|
|
326
|
-
}
|
|
327
|
-
return;
|
|
328
|
-
}
|
|
329
|
-
function mapDatabaseError(error) {
|
|
330
|
-
if (error instanceof HttpError) {
|
|
331
|
-
return error;
|
|
332
|
-
}
|
|
333
|
-
if (!isPostgresError(error)) {
|
|
334
|
-
const message = error instanceof Error ? error.message : "Database operation failed.";
|
|
335
|
-
return new BadRequestError(message);
|
|
336
|
-
}
|
|
337
|
-
const sqlState = getPostgresSqlState(error);
|
|
338
|
-
switch (sqlState) {
|
|
339
|
-
case "23505":
|
|
340
|
-
return new ConflictError(error.detail ?? "A record with these values already exists.", {
|
|
341
|
-
constraint: error.constraint
|
|
342
|
-
});
|
|
343
|
-
case "23503":
|
|
344
|
-
return new UnprocessableEntityError(error.detail ?? "Referenced record does not exist.", {
|
|
345
|
-
constraint: error.constraint
|
|
346
|
-
});
|
|
347
|
-
case "23502":
|
|
348
|
-
return new BadRequestError(error.detail ?? "Required field is missing.", {
|
|
349
|
-
constraint: error.constraint
|
|
350
|
-
});
|
|
351
|
-
case "23514":
|
|
352
|
-
return new BadRequestError(error.detail ?? "Value violates a database constraint.", {
|
|
353
|
-
constraint: error.constraint
|
|
354
|
-
});
|
|
355
|
-
default:
|
|
356
|
-
return new BadRequestError(error.message ?? "Database operation failed.", {
|
|
357
|
-
code: error.code,
|
|
358
|
-
sqlState
|
|
359
|
-
});
|
|
360
|
-
}
|
|
361
|
-
}
|
|
362
|
-
async function withDatabaseErrorHandling(operation) {
|
|
363
|
-
try {
|
|
364
|
-
return await operation();
|
|
365
|
-
} catch (error) {
|
|
366
|
-
throw mapDatabaseError(error);
|
|
367
|
-
}
|
|
368
|
-
}
|
|
369
|
-
|
|
370
|
-
// ../../src/core/database/query.ts
|
|
371
|
-
function quoteIdentifier(identifier) {
|
|
372
|
-
if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(identifier)) {
|
|
373
|
-
throw new Error(`Invalid SQL identifier: ${identifier}`);
|
|
374
|
-
}
|
|
375
|
-
return `"${identifier}"`;
|
|
376
|
-
}
|
|
377
|
-
function qualifyColumn(tableName, column) {
|
|
378
|
-
return `${quoteIdentifier(tableName)}.${quoteIdentifier(column)}`;
|
|
379
|
-
}
|
|
380
|
-
function resolveQualifiedColumn(defaultTable, columnName) {
|
|
381
|
-
if (columnName.includes(".")) {
|
|
382
|
-
const [table, column] = columnName.split(".", 2);
|
|
383
|
-
if (!table || !column) {
|
|
384
|
-
throw new Error(`Invalid qualified column: ${columnName}`);
|
|
385
|
-
}
|
|
386
|
-
return qualifyColumn(table, column);
|
|
387
|
-
}
|
|
388
|
-
return qualifyColumn(defaultTable, columnName);
|
|
389
|
-
}
|
|
390
|
-
function parseQualifiedColumn(reference) {
|
|
391
|
-
const [table, column] = reference.split(".", 2);
|
|
392
|
-
if (!table || !column) {
|
|
393
|
-
throw new Error(`Join columns must be qualified as table.column: ${reference}`);
|
|
394
|
-
}
|
|
395
|
-
return { table, column };
|
|
396
|
-
}
|
|
397
|
-
function normalizeDirection(direction = "ASC") {
|
|
398
|
-
return direction.toUpperCase() === "DESC" ? "DESC" : "ASC";
|
|
399
|
-
}
|
|
400
|
-
function isQueryOperator(value) {
|
|
401
|
-
return value !== null && !Array.isArray(value) && !(value instanceof Date) && typeof value === "object";
|
|
402
|
-
}
|
|
403
|
-
function pushParam(values, value) {
|
|
404
|
-
values.push(value);
|
|
405
|
-
return `$${values.length}`;
|
|
406
|
-
}
|
|
407
|
-
function buildInClause(column, values, params) {
|
|
408
|
-
if (values.length === 0) {
|
|
409
|
-
return "1 = 0";
|
|
410
|
-
}
|
|
411
|
-
const placeholders = values.map((value) => pushParam(params, value)).join(", ");
|
|
412
|
-
return `${column} IN (${placeholders})`;
|
|
413
|
-
}
|
|
414
|
-
function buildOperatorClauses(column, operator, params) {
|
|
415
|
-
const clauses = [];
|
|
416
|
-
if (operator.isNull === true) {
|
|
417
|
-
clauses.push(`${column} IS NULL`);
|
|
418
|
-
}
|
|
419
|
-
if (operator.isNull === false) {
|
|
420
|
-
clauses.push(`${column} IS NOT NULL`);
|
|
421
|
-
}
|
|
422
|
-
if (operator.eq !== undefined) {
|
|
423
|
-
if (operator.eq === null) {
|
|
424
|
-
clauses.push(`${column} IS NULL`);
|
|
425
|
-
} else {
|
|
426
|
-
clauses.push(`${column} = ${pushParam(params, operator.eq)}`);
|
|
427
|
-
}
|
|
428
|
-
}
|
|
429
|
-
if (operator.in !== undefined) {
|
|
430
|
-
clauses.push(buildInClause(column, operator.in, params));
|
|
431
|
-
}
|
|
432
|
-
if (operator.gt !== undefined) {
|
|
433
|
-
clauses.push(`${column} > ${pushParam(params, operator.gt)}`);
|
|
434
|
-
}
|
|
435
|
-
if (operator.gte !== undefined) {
|
|
436
|
-
clauses.push(`${column} >= ${pushParam(params, operator.gte)}`);
|
|
437
|
-
}
|
|
438
|
-
if (operator.lt !== undefined) {
|
|
439
|
-
clauses.push(`${column} < ${pushParam(params, operator.lt)}`);
|
|
440
|
-
}
|
|
441
|
-
if (operator.lte !== undefined) {
|
|
442
|
-
clauses.push(`${column} <= ${pushParam(params, operator.lte)}`);
|
|
443
|
-
}
|
|
444
|
-
if (operator.ilike !== undefined) {
|
|
445
|
-
clauses.push(`${column} ILIKE ${pushParam(params, `%${operator.ilike}%`)}`);
|
|
446
|
-
}
|
|
447
|
-
if (operator.tsMatch !== undefined) {
|
|
448
|
-
clauses.push(`${column} @@ plainto_tsquery('english', ${pushParam(params, operator.tsMatch)})`);
|
|
449
|
-
}
|
|
450
|
-
return clauses;
|
|
451
|
-
}
|
|
452
|
-
function appendWhereParts(tableName, where, params) {
|
|
453
|
-
const clauses = [];
|
|
454
|
-
for (const [columnName, filterValue] of Object.entries(where)) {
|
|
455
|
-
if (filterValue === undefined) {
|
|
456
|
-
continue;
|
|
457
|
-
}
|
|
458
|
-
const column = resolveQualifiedColumn(tableName, columnName);
|
|
459
|
-
if (Array.isArray(filterValue)) {
|
|
460
|
-
clauses.push(buildInClause(column, filterValue, params));
|
|
461
|
-
continue;
|
|
462
|
-
}
|
|
463
|
-
if (isQueryOperator(filterValue)) {
|
|
464
|
-
clauses.push(...buildOperatorClauses(column, filterValue, params));
|
|
465
|
-
continue;
|
|
466
|
-
}
|
|
467
|
-
if (filterValue === null) {
|
|
468
|
-
clauses.push(`${column} IS NULL`);
|
|
469
|
-
continue;
|
|
470
|
-
}
|
|
471
|
-
clauses.push(`${column} = ${pushParam(params, filterValue)}`);
|
|
472
|
-
}
|
|
473
|
-
return clauses.join(" AND ");
|
|
474
|
-
}
|
|
475
|
-
function buildWhereClause(tableName, where = {}) {
|
|
476
|
-
const params = [];
|
|
477
|
-
const body = appendWhereParts(tableName, where, params);
|
|
478
|
-
return {
|
|
479
|
-
clause: body.length > 0 ? ` WHERE ${body}` : "",
|
|
480
|
-
params
|
|
481
|
-
};
|
|
482
|
-
}
|
|
483
|
-
function buildWhereNodeClause(tableName, node, params) {
|
|
484
|
-
if ("where" in node) {
|
|
485
|
-
return appendWhereParts(tableName, node.where, params);
|
|
486
|
-
}
|
|
487
|
-
const grouped = buildWhereGroupClause(tableName, node.group, params);
|
|
488
|
-
if (!grouped) {
|
|
489
|
-
return "";
|
|
490
|
-
}
|
|
491
|
-
return grouped.includes(" OR ") ? `(${grouped})` : grouped;
|
|
492
|
-
}
|
|
493
|
-
function buildWhereGroupClause(tableName, nodes, params) {
|
|
494
|
-
let result = "";
|
|
495
|
-
for (const node of nodes) {
|
|
496
|
-
const part = buildWhereNodeClause(tableName, node, params);
|
|
497
|
-
if (!part) {
|
|
498
|
-
continue;
|
|
499
|
-
}
|
|
500
|
-
if (!result) {
|
|
501
|
-
result = part;
|
|
502
|
-
continue;
|
|
503
|
-
}
|
|
504
|
-
result = node.kind === "or" ? `${result} OR ${part}` : `${result} AND ${part}`;
|
|
505
|
-
}
|
|
506
|
-
if (!result) {
|
|
507
|
-
return "";
|
|
508
|
-
}
|
|
509
|
-
return result;
|
|
510
|
-
}
|
|
511
|
-
function buildAdvancedWhereClause(tableName, where = {}, whereNodes = [], params = []) {
|
|
512
|
-
const nodes = [];
|
|
513
|
-
if (Object.keys(where).length > 0) {
|
|
514
|
-
nodes.push({ kind: "and", where });
|
|
515
|
-
}
|
|
516
|
-
nodes.push(...whereNodes);
|
|
517
|
-
const combined = buildWhereGroupClause(tableName, nodes, params);
|
|
518
|
-
return {
|
|
519
|
-
clause: combined ? ` WHERE ${combined}` : "",
|
|
520
|
-
params
|
|
521
|
-
};
|
|
522
|
-
}
|
|
523
|
-
function resolveSoftDeleteColumn(table) {
|
|
524
|
-
if (!table.softDeletes) {
|
|
525
|
-
return null;
|
|
526
|
-
}
|
|
527
|
-
if (table.softDeletes === true) {
|
|
528
|
-
return "deleted_at";
|
|
529
|
-
}
|
|
530
|
-
return table.softDeletes.column ?? "deleted_at";
|
|
531
|
-
}
|
|
532
|
-
function appendSoftDeleteScope(table, options, clauses) {
|
|
533
|
-
const column = resolveSoftDeleteColumn(table);
|
|
534
|
-
if (!column) {
|
|
535
|
-
return;
|
|
536
|
-
}
|
|
537
|
-
const qualifiedColumn = qualifyColumn(table.name, column);
|
|
538
|
-
if (options.onlyTrashed) {
|
|
539
|
-
clauses.push(`${qualifiedColumn} IS NOT NULL`);
|
|
540
|
-
return;
|
|
541
|
-
}
|
|
542
|
-
if (!options.withTrashed) {
|
|
543
|
-
clauses.push(`${qualifiedColumn} IS NULL`);
|
|
544
|
-
}
|
|
545
|
-
}
|
|
546
|
-
function buildQueryWhereClause(table, options = {}, whereNodes = [], params = []) {
|
|
547
|
-
const { clause, params: whereParams } = buildAdvancedWhereClause(table.name, options.where ?? {}, whereNodes, params);
|
|
548
|
-
const softDeleteClauses = [];
|
|
549
|
-
appendSoftDeleteScope(table, options, softDeleteClauses);
|
|
550
|
-
if (softDeleteClauses.length === 0) {
|
|
551
|
-
return { clause, params: whereParams };
|
|
552
|
-
}
|
|
553
|
-
const base = clause.replace(/^ WHERE /, "");
|
|
554
|
-
const scope = softDeleteClauses.join(" AND ");
|
|
555
|
-
return {
|
|
556
|
-
clause: base ? ` WHERE (${base}) AND ${scope}` : ` WHERE ${scope}`,
|
|
557
|
-
params: whereParams
|
|
558
|
-
};
|
|
559
|
-
}
|
|
560
|
-
function isQueryOrder(value) {
|
|
561
|
-
return "column" in value;
|
|
562
|
-
}
|
|
563
|
-
function normalizeOrderBy(orderBy) {
|
|
564
|
-
if (!orderBy) {
|
|
565
|
-
return [];
|
|
566
|
-
}
|
|
567
|
-
if (Array.isArray(orderBy)) {
|
|
568
|
-
return orderBy;
|
|
569
|
-
}
|
|
570
|
-
if (isQueryOrder(orderBy)) {
|
|
571
|
-
return [orderBy];
|
|
572
|
-
}
|
|
573
|
-
return Object.entries(orderBy).map(([column, direction]) => ({
|
|
574
|
-
column,
|
|
575
|
-
direction
|
|
576
|
-
}));
|
|
577
|
-
}
|
|
578
|
-
function buildOrderByClause(tableName, orderBy) {
|
|
579
|
-
const parts = normalizeOrderBy(orderBy).map(({ column, direction }) => {
|
|
580
|
-
return `${resolveQualifiedColumn(tableName, column)} ${normalizeDirection(direction)}`;
|
|
581
|
-
});
|
|
582
|
-
return parts.length > 0 ? ` ORDER BY ${parts.join(", ")}` : "";
|
|
583
|
-
}
|
|
584
|
-
function buildGroupByClause(tableName, groupBy) {
|
|
585
|
-
if (!groupBy) {
|
|
586
|
-
return "";
|
|
587
|
-
}
|
|
588
|
-
const columns = (Array.isArray(groupBy) ? groupBy : [groupBy]).map((column) => String(column));
|
|
589
|
-
const parts = columns.map((column) => resolveQualifiedColumn(tableName, column));
|
|
590
|
-
return parts.length > 0 ? ` GROUP BY ${parts.join(", ")}` : "";
|
|
591
|
-
}
|
|
592
|
-
function buildHavingClause(tableName, having, params) {
|
|
593
|
-
if (!having) {
|
|
594
|
-
return "";
|
|
595
|
-
}
|
|
596
|
-
const body = appendWhereParts(tableName, having, params);
|
|
597
|
-
return body.length > 0 ? ` HAVING ${body}` : "";
|
|
598
|
-
}
|
|
599
|
-
function buildJoinClause(joins = []) {
|
|
600
|
-
return joins.map((join) => {
|
|
601
|
-
const joinType = join.type === "left" ? "LEFT JOIN" : "INNER JOIN";
|
|
602
|
-
const onClause = join.on.map(({ left, right }) => `${qualifyColumn(left.table, left.column)} = ${qualifyColumn(right.table, right.column)}`).join(" AND ");
|
|
603
|
-
return ` ${joinType} ${quoteIdentifier(join.table)} ON ${onClause}`;
|
|
604
|
-
}).join("");
|
|
605
|
-
}
|
|
606
|
-
function buildLimitClause(limit) {
|
|
607
|
-
if (limit === undefined) {
|
|
608
|
-
return "";
|
|
609
|
-
}
|
|
610
|
-
if (!Number.isInteger(limit) || limit <= 0) {
|
|
611
|
-
throw new Error("Query limit must be a positive integer.");
|
|
612
|
-
}
|
|
613
|
-
return ` LIMIT ${limit}`;
|
|
614
|
-
}
|
|
615
|
-
function buildOffsetClause(offset) {
|
|
616
|
-
if (offset === undefined) {
|
|
617
|
-
return "";
|
|
618
|
-
}
|
|
619
|
-
if (!Number.isInteger(offset) || offset < 0) {
|
|
620
|
-
throw new Error("Query offset must be a non-negative integer.");
|
|
621
|
-
}
|
|
622
|
-
return ` OFFSET ${offset}`;
|
|
623
|
-
}
|
|
624
|
-
function buildReturningColumns(table) {
|
|
625
|
-
return table.columns.map((column) => qualifyColumn(table.name, column)).join(", ");
|
|
626
|
-
}
|
|
627
|
-
function buildSelectList(table, select, params = []) {
|
|
628
|
-
if (!select || select.length === 0) {
|
|
629
|
-
return buildReturningColumns(table);
|
|
630
|
-
}
|
|
631
|
-
return select.map((item) => {
|
|
632
|
-
if (item.kind === "column") {
|
|
633
|
-
const column2 = qualifyColumn(item.table, item.column);
|
|
634
|
-
return item.as ? `${column2} AS ${quoteIdentifier(item.as)}` : column2;
|
|
635
|
-
}
|
|
636
|
-
if (item.kind === "literalText") {
|
|
637
|
-
return `${pushParam(params, item.value)}::text AS ${quoteIdentifier(item.as)}`;
|
|
638
|
-
}
|
|
639
|
-
const column = qualifyColumn(item.table, item.column);
|
|
640
|
-
const placeholder = pushParam(params, item.query);
|
|
641
|
-
return `ts_rank(${column}, plainto_tsquery('english', ${placeholder})) AS ${quoteIdentifier(item.as)}`;
|
|
642
|
-
}).join(", ");
|
|
643
|
-
}
|
|
644
|
-
function getDefinedColumnEntries(table, values, options = {}) {
|
|
645
|
-
const record = values;
|
|
646
|
-
const excluded = new Set(options.exclude ?? []);
|
|
647
|
-
return table.columns.flatMap((column) => {
|
|
648
|
-
if (excluded.has(column) || !Object.hasOwn(record, column)) {
|
|
649
|
-
return [];
|
|
650
|
-
}
|
|
651
|
-
const value = record[column];
|
|
652
|
-
if (value === undefined) {
|
|
653
|
-
return [];
|
|
654
|
-
}
|
|
655
|
-
return [[column, value]];
|
|
656
|
-
});
|
|
657
|
-
}
|
|
658
|
-
function buildSelectQuery(table, options = {}, whereNodes = []) {
|
|
659
|
-
const params = [];
|
|
660
|
-
const columns = buildSelectList(table, options.select, params);
|
|
661
|
-
const { clause } = buildQueryWhereClause(table, options, whereNodes, params);
|
|
662
|
-
const joins = buildJoinClause(options.joins);
|
|
663
|
-
const groupBy = buildGroupByClause(table.name, options.groupBy);
|
|
664
|
-
const havingClause = buildHavingClause(table.name, options.having, params);
|
|
665
|
-
const orderBy = buildOrderByClause(table.name, options.orderBy ?? table.defaultOrderBy);
|
|
666
|
-
const limit = buildLimitClause(options.limit);
|
|
667
|
-
const offset = buildOffsetClause(options.offset);
|
|
668
|
-
return {
|
|
669
|
-
text: `SELECT ${columns} FROM ${quoteIdentifier(table.name)}${joins}${clause}${groupBy}${havingClause}${orderBy}${limit}${offset}`,
|
|
670
|
-
params
|
|
671
|
-
};
|
|
672
|
-
}
|
|
673
|
-
function buildCountQuery(table, where = {}, options = {}, whereNodes = []) {
|
|
674
|
-
const params = [];
|
|
675
|
-
const { clause, params: whereParams } = buildQueryWhereClause(table, {
|
|
676
|
-
where,
|
|
677
|
-
withTrashed: options.withTrashed,
|
|
678
|
-
onlyTrashed: options.onlyTrashed
|
|
679
|
-
}, whereNodes);
|
|
680
|
-
params.push(...whereParams);
|
|
681
|
-
const joins = buildJoinClause(options.joins);
|
|
682
|
-
const groupBy = buildGroupByClause(table.name, options.groupBy);
|
|
683
|
-
return {
|
|
684
|
-
text: `SELECT COUNT(*) AS count FROM ${quoteIdentifier(table.name)}${joins}${clause}${groupBy}`,
|
|
685
|
-
params
|
|
686
|
-
};
|
|
687
|
-
}
|
|
688
|
-
function buildProjectionQuery(table, expression, alias, options = {}, whereNodes = []) {
|
|
689
|
-
assertSafeProjectionExpression(expression);
|
|
690
|
-
const params = [];
|
|
691
|
-
const { clause, params: whereParams } = buildQueryWhereClause(table, options, whereNodes);
|
|
692
|
-
params.push(...whereParams);
|
|
693
|
-
const joins = buildJoinClause(options.joins);
|
|
694
|
-
const groupBy = buildGroupByClause(table.name, options.groupBy);
|
|
695
|
-
const orderBy = buildOrderByClause(table.name, options.orderBy);
|
|
696
|
-
const limit = buildLimitClause(options.limit);
|
|
697
|
-
return {
|
|
698
|
-
text: `SELECT ${expression} AS ${quoteIdentifier(alias)} FROM ${quoteIdentifier(table.name)}${joins}${clause}${groupBy}${orderBy}${limit}`,
|
|
699
|
-
params
|
|
700
|
-
};
|
|
701
|
-
}
|
|
702
|
-
var SAFE_PROJECTION_EXPRESSION = /^(COUNT\(\*\)|(?:"[\w_]+"(?:\."[\w_]+")?)|(?:AVG|SUM|MIN|MAX)\((?:"[\w_]+"(?:\."[\w_]+")?)\))$/;
|
|
703
|
-
function assertSafeProjectionExpression(expression) {
|
|
704
|
-
if (!SAFE_PROJECTION_EXPRESSION.test(expression.trim())) {
|
|
705
|
-
throw new Error(`Unsafe projection expression: ${expression}`);
|
|
706
|
-
}
|
|
707
|
-
}
|
|
708
|
-
function buildGroupedCountQuery(table, column, where = {}, options = {}) {
|
|
709
|
-
const qualifiedColumn = qualifyColumn(table.name, column);
|
|
710
|
-
const { clause, params } = buildQueryWhereClause(table, {
|
|
711
|
-
where,
|
|
712
|
-
...options
|
|
713
|
-
});
|
|
714
|
-
return {
|
|
715
|
-
text: `SELECT ${qualifiedColumn} AS ${quoteIdentifier("value")}, COUNT(*) AS ${quoteIdentifier("count")} FROM ${quoteIdentifier(table.name)}${clause} GROUP BY ${qualifiedColumn} ORDER BY ${qualifiedColumn} ASC`,
|
|
716
|
-
params
|
|
717
|
-
};
|
|
718
|
-
}
|
|
719
|
-
function buildInsertQuery(table, values) {
|
|
720
|
-
const entries = getDefinedColumnEntries(table, values);
|
|
721
|
-
if (entries.length === 0) {
|
|
722
|
-
throw new Error(`Cannot insert into ${table.name} without any column values.`);
|
|
723
|
-
}
|
|
724
|
-
const params = [];
|
|
725
|
-
const columns = entries.map(([column]) => quoteIdentifier(column)).join(", ");
|
|
726
|
-
const placeholders = entries.map(([, value]) => pushParam(params, value)).join(", ");
|
|
727
|
-
const returningColumns = buildReturningColumns(table);
|
|
728
|
-
return {
|
|
729
|
-
text: `INSERT INTO ${quoteIdentifier(table.name)} (${columns}) VALUES (${placeholders}) RETURNING ${returningColumns}`,
|
|
730
|
-
params
|
|
731
|
-
};
|
|
732
|
-
}
|
|
733
|
-
function buildUpdateQuery(table, id, changes) {
|
|
734
|
-
const entries = getDefinedColumnEntries(table, changes, {
|
|
735
|
-
exclude: [table.primaryKey]
|
|
736
|
-
});
|
|
737
|
-
if (entries.length === 0) {
|
|
738
|
-
throw new Error(`Cannot update ${table.name} without any changed column values.`);
|
|
739
|
-
}
|
|
740
|
-
const params = [];
|
|
741
|
-
const setClause = entries.map(([column, value]) => `${quoteIdentifier(column)} = ${pushParam(params, value)}`).join(", ");
|
|
742
|
-
const primaryKeyPlaceholder = pushParam(params, id);
|
|
743
|
-
const returningColumns = buildReturningColumns(table);
|
|
744
|
-
const scopeClauses = [];
|
|
745
|
-
appendSoftDeleteScope(table, {}, scopeClauses);
|
|
746
|
-
const scopeSuffix = scopeClauses.length > 0 ? ` AND ${scopeClauses.join(" AND ")}` : "";
|
|
747
|
-
return {
|
|
748
|
-
text: `UPDATE ${quoteIdentifier(table.name)} SET ${setClause} WHERE ${quoteIdentifier(table.primaryKey)} = ${primaryKeyPlaceholder}${scopeSuffix} RETURNING ${returningColumns}`,
|
|
749
|
-
params
|
|
750
|
-
};
|
|
751
|
-
}
|
|
752
|
-
function buildSoftDeleteByIdQuery(table, id, deletedAt) {
|
|
753
|
-
const deletedAtColumn = resolveSoftDeleteColumn(table);
|
|
754
|
-
if (!deletedAtColumn) {
|
|
755
|
-
throw new Error(`Table ${table.name} does not support soft deletes.`);
|
|
756
|
-
}
|
|
757
|
-
const returningColumns = buildReturningColumns(table);
|
|
758
|
-
const scopeClauses = [];
|
|
759
|
-
appendSoftDeleteScope(table, {}, scopeClauses);
|
|
760
|
-
const scopeSuffix = scopeClauses.length > 0 ? ` AND ${scopeClauses.join(" AND ")}` : "";
|
|
761
|
-
return {
|
|
762
|
-
text: `UPDATE ${quoteIdentifier(table.name)} SET ${quoteIdentifier(deletedAtColumn)} = $1 WHERE ${quoteIdentifier(table.primaryKey)} = $2${scopeSuffix} RETURNING ${returningColumns}`,
|
|
763
|
-
params: [deletedAt, id]
|
|
764
|
-
};
|
|
765
|
-
}
|
|
766
|
-
function buildRestoreByIdQuery(table, id) {
|
|
767
|
-
const deletedAtColumn = resolveSoftDeleteColumn(table);
|
|
768
|
-
if (!deletedAtColumn) {
|
|
769
|
-
throw new Error(`Table ${table.name} does not support soft deletes.`);
|
|
770
|
-
}
|
|
771
|
-
const returningColumns = buildReturningColumns(table);
|
|
772
|
-
return {
|
|
773
|
-
text: `UPDATE ${quoteIdentifier(table.name)} SET ${quoteIdentifier(deletedAtColumn)} = $1 WHERE ${quoteIdentifier(table.primaryKey)} = $2 AND ${qualifyColumn(table.name, deletedAtColumn)} IS NOT NULL RETURNING ${returningColumns}`,
|
|
774
|
-
params: [null, id]
|
|
775
|
-
};
|
|
776
|
-
}
|
|
777
|
-
function buildDeleteByIdQuery(table, id) {
|
|
778
|
-
return {
|
|
779
|
-
text: `DELETE FROM ${quoteIdentifier(table.name)} WHERE ${quoteIdentifier(table.primaryKey)} = $1 RETURNING ${quoteIdentifier(table.primaryKey)} AS ${quoteIdentifier("deleted_id")}`,
|
|
780
|
-
params: [id]
|
|
781
|
-
};
|
|
782
|
-
}
|
|
783
|
-
|
|
784
|
-
// ../../src/core/database/relationships.ts
|
|
785
|
-
function hasMany(definition) {
|
|
786
|
-
return {
|
|
787
|
-
type: "hasMany",
|
|
788
|
-
...definition
|
|
789
|
-
};
|
|
790
|
-
}
|
|
791
|
-
function hasOne(definition) {
|
|
792
|
-
return {
|
|
793
|
-
type: "hasOne",
|
|
794
|
-
...definition
|
|
795
|
-
};
|
|
796
|
-
}
|
|
797
|
-
function belongsTo(definition) {
|
|
798
|
-
return {
|
|
799
|
-
type: "belongsTo",
|
|
800
|
-
...definition
|
|
801
|
-
};
|
|
802
|
-
}
|
|
803
|
-
function belongsToMany(definition) {
|
|
804
|
-
return {
|
|
805
|
-
type: "belongsToMany",
|
|
806
|
-
...definition
|
|
807
|
-
};
|
|
808
|
-
}
|
|
809
|
-
function indexHasManyRelation(parents, children, relation) {
|
|
810
|
-
const groups = new Map;
|
|
811
|
-
for (const parent of parents) {
|
|
812
|
-
groups.set(parent[relation.localKey], []);
|
|
813
|
-
}
|
|
814
|
-
for (const child of children) {
|
|
815
|
-
const key = child[relation.foreignKey];
|
|
816
|
-
const group = groups.get(key);
|
|
817
|
-
if (!group) {
|
|
818
|
-
continue;
|
|
819
|
-
}
|
|
820
|
-
group.push(child);
|
|
821
|
-
}
|
|
822
|
-
return groups;
|
|
823
|
-
}
|
|
824
|
-
function indexHasOneRelation(parents, children, relation) {
|
|
825
|
-
const grouped = indexHasManyRelation(parents, children, relation);
|
|
826
|
-
const result = new Map;
|
|
827
|
-
for (const parent of parents) {
|
|
828
|
-
const matches = grouped.get(parent[relation.localKey]) ?? [];
|
|
829
|
-
result.set(parent[relation.localKey], matches[0]);
|
|
830
|
-
}
|
|
831
|
-
return result;
|
|
832
|
-
}
|
|
833
|
-
function indexBelongsToRelation(children, parents, relation) {
|
|
834
|
-
const parentsById = new Map;
|
|
835
|
-
for (const parent of parents) {
|
|
836
|
-
parentsById.set(parent[relation.ownerKey], parent);
|
|
837
|
-
}
|
|
838
|
-
const result = new Map;
|
|
839
|
-
for (const child of children) {
|
|
840
|
-
const foreignKey = child[relation.foreignKey];
|
|
841
|
-
const parent = parentsById.get(foreignKey);
|
|
842
|
-
if (parent) {
|
|
843
|
-
result.set(foreignKey, parent);
|
|
844
|
-
}
|
|
845
|
-
}
|
|
846
|
-
return result;
|
|
847
|
-
}
|
|
848
|
-
function indexBelongsToManyRelation(parents, pivotRows, relatedRows, relation) {
|
|
849
|
-
const relatedById = new Map;
|
|
850
|
-
for (const related of relatedRows) {
|
|
851
|
-
relatedById.set(related[relation.relatedKey], related);
|
|
852
|
-
}
|
|
853
|
-
const groups = new Map;
|
|
854
|
-
for (const parent of parents) {
|
|
855
|
-
groups.set(parent[relation.parentKey], []);
|
|
856
|
-
}
|
|
857
|
-
for (const pivot of pivotRows) {
|
|
858
|
-
const parentId = pivot[relation.foreignPivotKey];
|
|
859
|
-
const relatedId = pivot[relation.relatedPivotKey];
|
|
860
|
-
const group = groups.get(parentId);
|
|
861
|
-
const related = relatedById.get(relatedId);
|
|
862
|
-
if (!group || !related) {
|
|
863
|
-
continue;
|
|
864
|
-
}
|
|
865
|
-
group.push(related);
|
|
866
|
-
}
|
|
867
|
-
return groups;
|
|
868
|
-
}
|
|
869
|
-
function morphMany(definition) {
|
|
870
|
-
return {
|
|
871
|
-
type: "morphMany",
|
|
872
|
-
...definition
|
|
873
|
-
};
|
|
874
|
-
}
|
|
875
|
-
function morphOne(definition) {
|
|
876
|
-
return {
|
|
877
|
-
type: "morphOne",
|
|
878
|
-
...definition
|
|
879
|
-
};
|
|
880
|
-
}
|
|
881
|
-
function morphTo(definition) {
|
|
882
|
-
return {
|
|
883
|
-
type: "morphTo",
|
|
884
|
-
...definition
|
|
885
|
-
};
|
|
886
|
-
}
|
|
887
|
-
function indexMorphManyRelation(parents, children, relation) {
|
|
888
|
-
const groups = new Map;
|
|
889
|
-
for (const parent of parents) {
|
|
890
|
-
groups.set(parent[relation.localKey], []);
|
|
891
|
-
}
|
|
892
|
-
for (const child of children) {
|
|
893
|
-
if (child[relation.morphTypeKey] !== relation.morphType) {
|
|
894
|
-
continue;
|
|
895
|
-
}
|
|
896
|
-
const key = child[relation.morphIdKey];
|
|
897
|
-
const group = groups.get(key);
|
|
898
|
-
if (!group) {
|
|
899
|
-
continue;
|
|
900
|
-
}
|
|
901
|
-
group.push(child);
|
|
902
|
-
}
|
|
903
|
-
return groups;
|
|
904
|
-
}
|
|
905
|
-
function indexMorphOneRelation(parents, children, relation) {
|
|
906
|
-
const grouped = indexMorphManyRelation(parents, children, relation);
|
|
907
|
-
const result = new Map;
|
|
908
|
-
for (const parent of parents) {
|
|
909
|
-
const matches = grouped.get(parent[relation.localKey]) ?? [];
|
|
910
|
-
result.set(parent[relation.localKey], matches[0]);
|
|
911
|
-
}
|
|
912
|
-
return result;
|
|
913
|
-
}
|
|
914
|
-
function indexMorphToRelation(children, parentsByType, relation) {
|
|
915
|
-
const result = new Map;
|
|
916
|
-
for (const child of children) {
|
|
917
|
-
const morphType = String(child[relation.morphTypeKey]);
|
|
918
|
-
const parents = parentsByType.get(morphType);
|
|
919
|
-
if (!parents) {
|
|
920
|
-
continue;
|
|
921
|
-
}
|
|
922
|
-
const parent = parents.get(child[relation.morphIdKey]);
|
|
923
|
-
if (parent) {
|
|
924
|
-
result.set(child[relation.morphIdKey], parent);
|
|
925
|
-
}
|
|
926
|
-
}
|
|
927
|
-
return result;
|
|
928
|
-
}
|
|
929
|
-
|
|
930
|
-
// ../../src/config/database.ts
|
|
931
|
-
function readInteger(name, fallback) {
|
|
932
|
-
const parsed = Number.parseInt(process.env[name] ?? String(fallback), 10);
|
|
933
|
-
return Number.isInteger(parsed) && parsed >= 0 ? parsed : fallback;
|
|
934
|
-
}
|
|
935
|
-
var databaseConfig = {
|
|
936
|
-
url: process.env.DATABASE_URL ?? "",
|
|
937
|
-
poolMax: readInteger("DB_POOL_MAX", 10),
|
|
938
|
-
idleTimeoutSeconds: readInteger("DB_POOL_IDLE_TIMEOUT", 30),
|
|
939
|
-
maxLifetimeSeconds: readInteger("DB_POOL_MAX_LIFETIME", 3600),
|
|
940
|
-
connectionTimeoutSeconds: readInteger("DB_CONNECTION_TIMEOUT", 10)
|
|
941
|
-
};
|
|
942
|
-
|
|
943
|
-
// ../../src/core/database/connectionContext.ts
|
|
944
|
-
import { AsyncLocalStorage } from "async_hooks";
|
|
945
|
-
var activeConnection = new AsyncLocalStorage;
|
|
946
|
-
function runWithDatabaseConnection(connection, callback) {
|
|
947
|
-
return activeConnection.run(connection, callback);
|
|
948
|
-
}
|
|
949
|
-
function getActiveDatabaseConnection(fallback) {
|
|
950
|
-
return activeConnection.getStore() ?? fallback;
|
|
951
|
-
}
|
|
952
|
-
|
|
953
|
-
// ../../src/db/connection/createConnection.ts
|
|
954
|
-
var {SQL } = globalThis.Bun;
|
|
955
|
-
function createDatabaseConnection(config) {
|
|
956
|
-
if (!config.url) {
|
|
957
|
-
throw new Error("DATABASE_URL is not configured. Set DATABASE_URL before starting the app or running integration tests.");
|
|
958
|
-
}
|
|
959
|
-
return new SQL({
|
|
960
|
-
url: config.url,
|
|
961
|
-
max: config.poolMax,
|
|
962
|
-
idleTimeout: config.idleTimeoutSeconds,
|
|
963
|
-
maxLifetime: config.maxLifetimeSeconds,
|
|
964
|
-
connectionTimeout: config.connectionTimeoutSeconds
|
|
965
|
-
});
|
|
966
|
-
}
|
|
967
|
-
|
|
968
|
-
// ../../src/db/connection/index.ts
|
|
969
|
-
var connectionHolder = {
|
|
970
|
-
connection: null
|
|
971
|
-
};
|
|
972
|
-
function getDatabase() {
|
|
973
|
-
if (!connectionHolder.connection) {
|
|
974
|
-
connectionHolder.connection = createDatabaseConnection(databaseConfig);
|
|
975
|
-
}
|
|
976
|
-
return connectionHolder.connection;
|
|
977
|
-
}
|
|
978
|
-
var POOL_CONNECTION_METHODS = new Set(["begin", "close", "connect"]);
|
|
979
|
-
function resolveDatabase() {
|
|
980
|
-
return getActiveDatabaseConnection(getDatabase());
|
|
981
|
-
}
|
|
982
|
-
function resolveDatabaseForProperty(property) {
|
|
983
|
-
if (typeof property === "string" && POOL_CONNECTION_METHODS.has(property)) {
|
|
984
|
-
return getDatabase();
|
|
985
|
-
}
|
|
986
|
-
return resolveDatabase();
|
|
987
|
-
}
|
|
988
|
-
var db = new Proxy(function database() {}, {
|
|
989
|
-
apply(_target, _thisArg, args) {
|
|
990
|
-
return resolveDatabase()(...args);
|
|
991
|
-
},
|
|
992
|
-
get(_target, property) {
|
|
993
|
-
const connection = resolveDatabaseForProperty(property);
|
|
994
|
-
const value = connection[property];
|
|
995
|
-
return typeof value === "function" ? value.bind(connection) : value;
|
|
996
|
-
}
|
|
997
|
-
});
|
|
998
|
-
var connection_default = db;
|
|
999
|
-
|
|
1000
|
-
// ../../src/core/database/boundConnection.ts
|
|
1001
|
-
var boundConnectionHolder = {
|
|
1002
|
-
connection: null
|
|
1003
|
-
};
|
|
1004
|
-
function bindDatabaseConnection(connection) {
|
|
1005
|
-
boundConnectionHolder.connection = connection;
|
|
1006
|
-
}
|
|
1007
|
-
function getBoundDatabaseConnection() {
|
|
1008
|
-
return boundConnectionHolder.connection;
|
|
1009
|
-
}
|
|
1010
|
-
|
|
1011
|
-
// ../../src/core/database/repositoryConnection.ts
|
|
1012
|
-
function resolveRepositoryConnection() {
|
|
1013
|
-
return getBoundDatabaseConnection() ?? connection_default;
|
|
1014
|
-
}
|
|
1015
|
-
var repositoryConnection = new Proxy({}, {
|
|
1016
|
-
get(_target, property) {
|
|
1017
|
-
const connection = resolveRepositoryConnection();
|
|
1018
|
-
const value = connection[property];
|
|
1019
|
-
return typeof value === "function" ? value.bind(connection) : value;
|
|
1020
|
-
}
|
|
1021
|
-
});
|
|
1022
|
-
|
|
1023
|
-
// ../../src/core/database/whereBuilder.ts
|
|
1024
|
-
class WhereBuilder {
|
|
1025
|
-
nodes = [];
|
|
1026
|
-
where(where) {
|
|
1027
|
-
this.nodes.push({ kind: "and", where });
|
|
1028
|
-
return this;
|
|
1029
|
-
}
|
|
1030
|
-
orWhere(where) {
|
|
1031
|
-
this.nodes.push({ kind: "or", where });
|
|
1032
|
-
return this;
|
|
1033
|
-
}
|
|
1034
|
-
whereGroup(fn) {
|
|
1035
|
-
const nested = new WhereBuilder;
|
|
1036
|
-
fn(nested);
|
|
1037
|
-
if (nested.nodes.length > 0) {
|
|
1038
|
-
this.nodes.push({ kind: "and", group: nested.nodes });
|
|
1039
|
-
}
|
|
1040
|
-
return this;
|
|
1041
|
-
}
|
|
1042
|
-
orWhereGroup(fn) {
|
|
1043
|
-
const nested = new WhereBuilder;
|
|
1044
|
-
fn(nested);
|
|
1045
|
-
if (nested.nodes.length > 0) {
|
|
1046
|
-
this.nodes.push({ kind: "or", group: nested.nodes });
|
|
1047
|
-
}
|
|
1048
|
-
return this;
|
|
1049
|
-
}
|
|
1050
|
-
}
|
|
1051
|
-
|
|
1052
|
-
// ../../src/core/database/repositoryQuery.ts
|
|
1053
|
-
class RepositoryQuery {
|
|
1054
|
-
repository;
|
|
1055
|
-
whereClause;
|
|
1056
|
-
queryOptions;
|
|
1057
|
-
eagerLoads = [];
|
|
1058
|
-
whereNodes = [];
|
|
1059
|
-
constructor(repository, whereClause = {}, queryOptions = {}) {
|
|
1060
|
-
this.repository = repository;
|
|
1061
|
-
this.whereClause = whereClause;
|
|
1062
|
-
this.queryOptions = queryOptions;
|
|
1063
|
-
}
|
|
1064
|
-
where(input) {
|
|
1065
|
-
if (typeof input === "function") {
|
|
1066
|
-
const builder = new WhereBuilder;
|
|
1067
|
-
input(builder);
|
|
1068
|
-
this.whereNodes.push(...builder.nodes);
|
|
1069
|
-
return this;
|
|
1070
|
-
}
|
|
1071
|
-
this.whereClause = { ...this.whereClause, ...input };
|
|
1072
|
-
return this;
|
|
1073
|
-
}
|
|
1074
|
-
orWhere(input) {
|
|
1075
|
-
if (typeof input === "function") {
|
|
1076
|
-
const builder = new WhereBuilder;
|
|
1077
|
-
input(builder);
|
|
1078
|
-
if (builder.nodes.length > 0) {
|
|
1079
|
-
this.whereNodes.push({ kind: "or", group: builder.nodes });
|
|
1080
|
-
}
|
|
1081
|
-
return this;
|
|
1082
|
-
}
|
|
1083
|
-
this.whereNodes.push({ kind: "or", where: input });
|
|
1084
|
-
return this;
|
|
1085
|
-
}
|
|
1086
|
-
orderBy(orderBy) {
|
|
1087
|
-
this.queryOptions = { ...this.queryOptions, orderBy };
|
|
1088
|
-
return this;
|
|
1089
|
-
}
|
|
1090
|
-
limit(limit) {
|
|
1091
|
-
this.queryOptions = { ...this.queryOptions, limit };
|
|
1092
|
-
return this;
|
|
1093
|
-
}
|
|
1094
|
-
offset(offset) {
|
|
1095
|
-
this.queryOptions = { ...this.queryOptions, offset };
|
|
1096
|
-
return this;
|
|
1097
|
-
}
|
|
1098
|
-
join(left, right) {
|
|
1099
|
-
return this.addJoin("inner", left, right);
|
|
1100
|
-
}
|
|
1101
|
-
leftJoin(left, right) {
|
|
1102
|
-
return this.addJoin("left", left, right);
|
|
1103
|
-
}
|
|
1104
|
-
groupBy(groupBy) {
|
|
1105
|
-
this.queryOptions = { ...this.queryOptions, groupBy };
|
|
1106
|
-
return this;
|
|
1107
|
-
}
|
|
1108
|
-
having(having) {
|
|
1109
|
-
this.queryOptions = { ...this.queryOptions, having };
|
|
1110
|
-
return this;
|
|
1111
|
-
}
|
|
1112
|
-
withHasMany(as, relation, childRepository, options = {}) {
|
|
1113
|
-
this.eagerLoads.push({
|
|
1114
|
-
kind: "hasMany",
|
|
1115
|
-
as,
|
|
1116
|
-
relation,
|
|
1117
|
-
repository: childRepository,
|
|
1118
|
-
options
|
|
1119
|
-
});
|
|
1120
|
-
return this;
|
|
1121
|
-
}
|
|
1122
|
-
withBelongsTo(as, relation, parentRepository, options = {}) {
|
|
1123
|
-
this.eagerLoads.push({
|
|
1124
|
-
kind: "belongsTo",
|
|
1125
|
-
as,
|
|
1126
|
-
relation,
|
|
1127
|
-
repository: parentRepository,
|
|
1128
|
-
options
|
|
1129
|
-
});
|
|
1130
|
-
return this;
|
|
1131
|
-
}
|
|
1132
|
-
withMorphMany(as, relation, childRepository, options = {}) {
|
|
1133
|
-
this.eagerLoads.push({
|
|
1134
|
-
kind: "morphMany",
|
|
1135
|
-
as,
|
|
1136
|
-
relation,
|
|
1137
|
-
repository: childRepository,
|
|
1138
|
-
options
|
|
1139
|
-
});
|
|
1140
|
-
return this;
|
|
1141
|
-
}
|
|
1142
|
-
withMorphOne(as, relation, childRepository, options = {}) {
|
|
1143
|
-
this.eagerLoads.push({
|
|
1144
|
-
kind: "morphOne",
|
|
1145
|
-
as,
|
|
1146
|
-
relation,
|
|
1147
|
-
repository: childRepository,
|
|
1148
|
-
options
|
|
1149
|
-
});
|
|
1150
|
-
return this;
|
|
1151
|
-
}
|
|
1152
|
-
withMorphTo(as, relation, repositoriesByType, options = {}) {
|
|
1153
|
-
this.eagerLoads.push({
|
|
1154
|
-
kind: "morphTo",
|
|
1155
|
-
as,
|
|
1156
|
-
relation,
|
|
1157
|
-
repository: this.repository,
|
|
1158
|
-
morphRepositories: repositoriesByType,
|
|
1159
|
-
options
|
|
1160
|
-
});
|
|
1161
|
-
return this;
|
|
1162
|
-
}
|
|
1163
|
-
async get() {
|
|
1164
|
-
const rows = await this.repository.findAll(this.buildOptions());
|
|
1165
|
-
return await this.attach(rows);
|
|
1166
|
-
}
|
|
1167
|
-
async first() {
|
|
1168
|
-
const rows = await this.get();
|
|
1169
|
-
return rows[0] ?? null;
|
|
1170
|
-
}
|
|
1171
|
-
async paginate(options) {
|
|
1172
|
-
return await this.repository.paginate({
|
|
1173
|
-
...this.buildOptions(),
|
|
1174
|
-
page: options.page,
|
|
1175
|
-
perPage: options.perPage
|
|
1176
|
-
});
|
|
1177
|
-
}
|
|
1178
|
-
buildOptions() {
|
|
1179
|
-
return {
|
|
1180
|
-
...this.queryOptions,
|
|
1181
|
-
where: this.whereClause,
|
|
1182
|
-
whereNodes: this.whereNodes
|
|
1183
|
-
};
|
|
1184
|
-
}
|
|
1185
|
-
addJoin(type, left, right) {
|
|
1186
|
-
const leftRef = parseQualifiedColumn(left);
|
|
1187
|
-
const rightRef = parseQualifiedColumn(right);
|
|
1188
|
-
const table = type === "inner" ? rightRef.table : rightRef.table;
|
|
1189
|
-
const joins = this.queryOptions.joins ?? [];
|
|
1190
|
-
const existing = joins.find((join) => join.table === table && join.type === type);
|
|
1191
|
-
if (existing) {
|
|
1192
|
-
existing.on.push({ left: leftRef, right: rightRef });
|
|
1193
|
-
return this;
|
|
1194
|
-
}
|
|
1195
|
-
this.queryOptions = {
|
|
1196
|
-
...this.queryOptions,
|
|
1197
|
-
joins: [
|
|
1198
|
-
...joins,
|
|
1199
|
-
{
|
|
1200
|
-
type,
|
|
1201
|
-
table,
|
|
1202
|
-
on: [{ left: leftRef, right: rightRef }]
|
|
1203
|
-
}
|
|
1204
|
-
]
|
|
1205
|
-
};
|
|
1206
|
-
return this;
|
|
1207
|
-
}
|
|
1208
|
-
async attach(rows) {
|
|
1209
|
-
if (rows.length === 0 || this.eagerLoads.length === 0) {
|
|
1210
|
-
return rows.map((row) => ({ ...row }));
|
|
1211
|
-
}
|
|
1212
|
-
let result = rows.map((row) => ({ ...row }));
|
|
1213
|
-
for (const load of this.eagerLoads) {
|
|
1214
|
-
if (load.kind === "hasMany") {
|
|
1215
|
-
const relation2 = load.relation;
|
|
1216
|
-
const grouped2 = await load.repository.withConnection(this.repository.getConnection()).loadHasManyForParents(rows, relation2, load.options);
|
|
1217
|
-
result = result.map((row) => ({
|
|
1218
|
-
...row,
|
|
1219
|
-
[load.as]: grouped2.get(row[relation2.localKey]) ?? []
|
|
1220
|
-
}));
|
|
1221
|
-
continue;
|
|
1222
|
-
}
|
|
1223
|
-
if (load.kind === "morphMany") {
|
|
1224
|
-
const relation2 = load.relation;
|
|
1225
|
-
const grouped2 = await load.repository.withConnection(this.repository.getConnection()).loadMorphManyForParents(rows, relation2, load.options);
|
|
1226
|
-
result = result.map((row) => ({
|
|
1227
|
-
...row,
|
|
1228
|
-
[load.as]: grouped2.get(row[relation2.localKey]) ?? []
|
|
1229
|
-
}));
|
|
1230
|
-
continue;
|
|
1231
|
-
}
|
|
1232
|
-
if (load.kind === "morphOne") {
|
|
1233
|
-
const relation2 = load.relation;
|
|
1234
|
-
const grouped2 = await load.repository.withConnection(this.repository.getConnection()).loadMorphOneForParents(rows, relation2, load.options);
|
|
1235
|
-
result = result.map((row) => ({
|
|
1236
|
-
...row,
|
|
1237
|
-
[load.as]: grouped2.get(row[relation2.localKey])
|
|
1238
|
-
}));
|
|
1239
|
-
continue;
|
|
1240
|
-
}
|
|
1241
|
-
if (load.kind === "morphTo") {
|
|
1242
|
-
const relation2 = load.relation;
|
|
1243
|
-
const grouped2 = await this.repository.loadMorphToForChildren(rows, relation2, load.morphRepositories ?? new Map, load.options);
|
|
1244
|
-
result = result.map((row) => ({
|
|
1245
|
-
...row,
|
|
1246
|
-
[load.as]: grouped2.get(row[relation2.morphIdKey])
|
|
1247
|
-
}));
|
|
1248
|
-
continue;
|
|
1249
|
-
}
|
|
1250
|
-
const relation = load.relation;
|
|
1251
|
-
const grouped = await this.repository.loadBelongsToForParents(rows, relation, load.repository, load.options);
|
|
1252
|
-
result = result.map((row) => ({
|
|
1253
|
-
...row,
|
|
1254
|
-
[load.as]: grouped.get(row[relation.foreignKey])
|
|
1255
|
-
}));
|
|
1256
|
-
}
|
|
1257
|
-
return result;
|
|
1258
|
-
}
|
|
1259
|
-
}
|
|
1260
|
-
|
|
1261
|
-
// ../../src/core/database/baseRepository.ts
|
|
1262
|
-
class BaseRepository {
|
|
1263
|
-
table;
|
|
1264
|
-
connection;
|
|
1265
|
-
constructor(table, connection = repositoryConnection) {
|
|
1266
|
-
this.table = table;
|
|
1267
|
-
this.connection = connection;
|
|
1268
|
-
}
|
|
1269
|
-
async findAll(options = {}) {
|
|
1270
|
-
return await withDatabaseErrorHandling(async () => {
|
|
1271
|
-
const { whereNodes, ...queryOptions } = options;
|
|
1272
|
-
const { text, params } = buildSelectQuery(this.table, queryOptions, whereNodes ?? []);
|
|
1273
|
-
return await this.connection.unsafe(text, params);
|
|
1274
|
-
});
|
|
1275
|
-
}
|
|
1276
|
-
async paginate(options) {
|
|
1277
|
-
const { whereNodes, where = {}, page, perPage, ...queryOptions } = options;
|
|
1278
|
-
const total = await this.countWhere(where, {
|
|
1279
|
-
withTrashed: options.withTrashed,
|
|
1280
|
-
onlyTrashed: options.onlyTrashed,
|
|
1281
|
-
joins: options.joins,
|
|
1282
|
-
groupBy: options.groupBy
|
|
1283
|
-
}, whereNodes);
|
|
1284
|
-
const offset = (page - 1) * perPage;
|
|
1285
|
-
const data = await this.findAll({
|
|
1286
|
-
...queryOptions,
|
|
1287
|
-
where,
|
|
1288
|
-
whereNodes,
|
|
1289
|
-
limit: perPage,
|
|
1290
|
-
offset
|
|
1291
|
-
});
|
|
1292
|
-
return {
|
|
1293
|
-
data,
|
|
1294
|
-
meta: buildPaginationMeta({ page, perPage, total })
|
|
1295
|
-
};
|
|
1296
|
-
}
|
|
1297
|
-
async chunk(count, callback, options = {}) {
|
|
1298
|
-
if (!Number.isInteger(count) || count <= 0) {
|
|
1299
|
-
throw new Error("Chunk size must be a positive integer.");
|
|
1300
|
-
}
|
|
1301
|
-
let offset = 0;
|
|
1302
|
-
while (true) {
|
|
1303
|
-
const rows = await this.findAll({
|
|
1304
|
-
...options,
|
|
1305
|
-
limit: count,
|
|
1306
|
-
offset
|
|
1307
|
-
});
|
|
1308
|
-
if (rows.length === 0) {
|
|
1309
|
-
return;
|
|
1310
|
-
}
|
|
1311
|
-
const shouldContinue = await callback(rows);
|
|
1312
|
-
if (shouldContinue === false || rows.length < count) {
|
|
1313
|
-
return;
|
|
1314
|
-
}
|
|
1315
|
-
offset += count;
|
|
1316
|
-
}
|
|
1317
|
-
}
|
|
1318
|
-
async cursorPaginate(options) {
|
|
1319
|
-
const {
|
|
1320
|
-
perPage,
|
|
1321
|
-
cursor,
|
|
1322
|
-
cursorColumn = this.table.primaryKey,
|
|
1323
|
-
direction = "asc",
|
|
1324
|
-
where = {},
|
|
1325
|
-
whereNodes,
|
|
1326
|
-
...queryOptions
|
|
1327
|
-
} = options;
|
|
1328
|
-
if (!Number.isInteger(perPage) || perPage <= 0) {
|
|
1329
|
-
throw new Error("Cursor page size must be a positive integer.");
|
|
1330
|
-
}
|
|
1331
|
-
const cursorWhere = { ...where };
|
|
1332
|
-
if (cursor !== undefined) {
|
|
1333
|
-
cursorWhere[cursorColumn] = direction === "asc" ? { gt: cursor } : { lt: cursor };
|
|
1334
|
-
}
|
|
1335
|
-
const rows = await this.findAll({
|
|
1336
|
-
...queryOptions,
|
|
1337
|
-
where: cursorWhere,
|
|
1338
|
-
whereNodes,
|
|
1339
|
-
orderBy: { [cursorColumn]: direction },
|
|
1340
|
-
limit: perPage + 1
|
|
1341
|
-
});
|
|
1342
|
-
const hasMore = rows.length > perPage;
|
|
1343
|
-
const data = hasMore ? rows.slice(0, perPage) : rows;
|
|
1344
|
-
const nextCursor = hasMore ? data[data.length - 1]?.[cursorColumn] ?? null : null;
|
|
1345
|
-
const prevCursor = cursor ?? null;
|
|
1346
|
-
return {
|
|
1347
|
-
data,
|
|
1348
|
-
meta: {
|
|
1349
|
-
per_page: perPage,
|
|
1350
|
-
next_cursor: nextCursor,
|
|
1351
|
-
prev_cursor: prevCursor,
|
|
1352
|
-
has_more: hasMore
|
|
1353
|
-
}
|
|
1354
|
-
};
|
|
1355
|
-
}
|
|
1356
|
-
async findById(id) {
|
|
1357
|
-
return await this.firstOrNull({
|
|
1358
|
-
[this.table.primaryKey]: id
|
|
1359
|
-
});
|
|
1360
|
-
}
|
|
1361
|
-
async findByIdOrThrow(id, errorFactory) {
|
|
1362
|
-
const record = await this.findById(id);
|
|
1363
|
-
if (record) {
|
|
1364
|
-
return record;
|
|
1365
|
-
}
|
|
1366
|
-
throw errorFactory?.(id) ?? new Error(`${this.table.name} ${String(id)} was not found.`);
|
|
1367
|
-
}
|
|
1368
|
-
async findByIds(ids) {
|
|
1369
|
-
const uniqueIds = [...new Set(ids)];
|
|
1370
|
-
if (uniqueIds.length === 0) {
|
|
1371
|
-
return [];
|
|
1372
|
-
}
|
|
1373
|
-
return await this.findWhere({
|
|
1374
|
-
[this.table.primaryKey]: uniqueIds
|
|
1375
|
-
});
|
|
1376
|
-
}
|
|
1377
|
-
async firstOrNull(where, options = {}) {
|
|
1378
|
-
const [record] = await this.findAll({ ...options, where, limit: 1 });
|
|
1379
|
-
return record ?? null;
|
|
1380
|
-
}
|
|
1381
|
-
async create(values) {
|
|
1382
|
-
return await withDatabaseErrorHandling(async () => {
|
|
1383
|
-
const { text, params } = buildInsertQuery(this.table, values);
|
|
1384
|
-
const [record] = await this.connection.unsafe(text, params);
|
|
1385
|
-
if (!record) {
|
|
1386
|
-
throw new Error(`Insert into ${this.table.name} did not return a record.`);
|
|
1387
|
-
}
|
|
1388
|
-
const entity = record;
|
|
1389
|
-
await eventBus.dispatch(modelEventName(this.table.name, "created"), entity);
|
|
1390
|
-
return entity;
|
|
1391
|
-
});
|
|
1392
|
-
}
|
|
1393
|
-
async updateById(id, changes) {
|
|
1394
|
-
return await withDatabaseErrorHandling(async () => {
|
|
1395
|
-
const { text, params } = buildUpdateQuery(this.table, id, changes);
|
|
1396
|
-
const [record] = await this.connection.unsafe(text, params);
|
|
1397
|
-
const entity = record ?? null;
|
|
1398
|
-
if (entity) {
|
|
1399
|
-
await eventBus.dispatch(modelEventName(this.table.name, "updated"), entity);
|
|
1400
|
-
}
|
|
1401
|
-
return entity;
|
|
1402
|
-
});
|
|
1403
|
-
}
|
|
1404
|
-
async updateByIdOrThrow(id, changes, errorFactory) {
|
|
1405
|
-
const record = await this.updateById(id, changes);
|
|
1406
|
-
if (record) {
|
|
1407
|
-
return record;
|
|
1408
|
-
}
|
|
1409
|
-
throw errorFactory?.(id) ?? new Error(`${this.table.name} ${String(id)} was not found.`);
|
|
1410
|
-
}
|
|
1411
|
-
async deleteById(id) {
|
|
1412
|
-
if (resolveSoftDeleteColumn(this.table)) {
|
|
1413
|
-
return await this.softDeleteById(id);
|
|
1414
|
-
}
|
|
1415
|
-
return await this.forceDeleteById(id);
|
|
1416
|
-
}
|
|
1417
|
-
async softDeleteById(id) {
|
|
1418
|
-
return await withDatabaseErrorHandling(async () => {
|
|
1419
|
-
const { text, params } = buildSoftDeleteByIdQuery(this.table, id, new Date);
|
|
1420
|
-
const [record] = await this.connection.unsafe(text, params);
|
|
1421
|
-
if (!record) {
|
|
1422
|
-
return false;
|
|
1423
|
-
}
|
|
1424
|
-
await eventBus.dispatch(modelEventName(this.table.name, "deleted"), record);
|
|
1425
|
-
return true;
|
|
1426
|
-
});
|
|
1427
|
-
}
|
|
1428
|
-
async forceDeleteById(id) {
|
|
1429
|
-
return await withDatabaseErrorHandling(async () => {
|
|
1430
|
-
const { text, params } = buildDeleteByIdQuery(this.table, id);
|
|
1431
|
-
const [row] = await this.connection.unsafe(text, params);
|
|
1432
|
-
if (!row) {
|
|
1433
|
-
return false;
|
|
1434
|
-
}
|
|
1435
|
-
await eventBus.dispatch(modelEventName(this.table.name, "force-deleted"), {
|
|
1436
|
-
id
|
|
1437
|
-
});
|
|
1438
|
-
return true;
|
|
1439
|
-
});
|
|
1440
|
-
}
|
|
1441
|
-
async restoreById(id) {
|
|
1442
|
-
return await withDatabaseErrorHandling(async () => {
|
|
1443
|
-
const { text, params } = buildRestoreByIdQuery(this.table, id);
|
|
1444
|
-
const [record] = await this.connection.unsafe(text, params);
|
|
1445
|
-
if (!record) {
|
|
1446
|
-
return null;
|
|
1447
|
-
}
|
|
1448
|
-
const entity = record;
|
|
1449
|
-
await eventBus.dispatch(modelEventName(this.table.name, "restored"), entity);
|
|
1450
|
-
return entity;
|
|
1451
|
-
});
|
|
1452
|
-
}
|
|
1453
|
-
withConnection(connection) {
|
|
1454
|
-
const clone = Object.create(Object.getPrototypeOf(this));
|
|
1455
|
-
Object.assign(clone, this);
|
|
1456
|
-
clone.connection = connection;
|
|
1457
|
-
return clone;
|
|
1458
|
-
}
|
|
1459
|
-
getConnection() {
|
|
1460
|
-
return this.connection;
|
|
1461
|
-
}
|
|
1462
|
-
getTable() {
|
|
1463
|
-
return this.table;
|
|
1464
|
-
}
|
|
1465
|
-
query(where = {}) {
|
|
1466
|
-
return new RepositoryQuery(this, where);
|
|
1467
|
-
}
|
|
1468
|
-
async findWhere(where, options = {}) {
|
|
1469
|
-
return await this.findAll({ ...options, where });
|
|
1470
|
-
}
|
|
1471
|
-
async countWhere(where = {}, options = {}, whereNodes = []) {
|
|
1472
|
-
const { text, params } = buildCountQuery(this.table, where, options, whereNodes);
|
|
1473
|
-
const [row] = await this.connection.unsafe(text, params);
|
|
1474
|
-
return Number(row?.count ?? 0);
|
|
1475
|
-
}
|
|
1476
|
-
async averageColumn(column, where = {}) {
|
|
1477
|
-
const qualifiedColumn = qualifyColumn(this.table.name, column);
|
|
1478
|
-
return await this.averageExpression(`AVG(${qualifiedColumn})`, "value", where);
|
|
1479
|
-
}
|
|
1480
|
-
async averageExpression(expression, alias, where = {}) {
|
|
1481
|
-
const { text, params } = buildProjectionQuery(this.table, expression, alias, { where });
|
|
1482
|
-
const [row] = await this.connection.unsafe(text, params);
|
|
1483
|
-
return Math.round(Number(row?.[alias] ?? 0));
|
|
1484
|
-
}
|
|
1485
|
-
async pluckNumberValues(expression, alias, options = {}) {
|
|
1486
|
-
const { text, params } = buildProjectionQuery(this.table, expression, alias, options);
|
|
1487
|
-
const rows = await this.connection.unsafe(text, params);
|
|
1488
|
-
return rows.flatMap((row) => {
|
|
1489
|
-
const value = row[alias];
|
|
1490
|
-
return value === null || value === undefined ? [] : [Number(value)];
|
|
1491
|
-
});
|
|
1492
|
-
}
|
|
1493
|
-
async countGroupedBy(column, where = {}) {
|
|
1494
|
-
const { text, params } = buildGroupedCountQuery(this.table, column, where);
|
|
1495
|
-
const rows = await this.connection.unsafe(text, params);
|
|
1496
|
-
return rows.map(({ value, count }) => ({
|
|
1497
|
-
value,
|
|
1498
|
-
count: Number(count)
|
|
1499
|
-
}));
|
|
1500
|
-
}
|
|
1501
|
-
async findByHasManyRelation(relation, parentId, options = {}) {
|
|
1502
|
-
return await this.findWhere({
|
|
1503
|
-
[relation.foreignKey]: parentId
|
|
1504
|
-
}, options);
|
|
1505
|
-
}
|
|
1506
|
-
async loadHasManyForParents(parents, relation, options = {}) {
|
|
1507
|
-
if (parents.length === 0) {
|
|
1508
|
-
return indexHasManyRelation(parents, [], relation);
|
|
1509
|
-
}
|
|
1510
|
-
const parentIds = [...new Set(parents.map((parent) => parent[relation.localKey]))];
|
|
1511
|
-
const children = await this.findWhere({
|
|
1512
|
-
[relation.foreignKey]: parentIds
|
|
1513
|
-
}, options);
|
|
1514
|
-
return indexHasManyRelation(parents, children, relation);
|
|
1515
|
-
}
|
|
1516
|
-
async loadBelongsToForParents(children, relation, parentRepository, options = {}) {
|
|
1517
|
-
if (children.length === 0) {
|
|
1518
|
-
return new Map;
|
|
1519
|
-
}
|
|
1520
|
-
const ownerIds = [...new Set(children.map((child) => child[relation.foreignKey]))];
|
|
1521
|
-
const parents = await parentRepository.withConnection(this.connection).findWhere({
|
|
1522
|
-
[relation.ownerKey]: ownerIds
|
|
1523
|
-
}, options);
|
|
1524
|
-
return indexBelongsToRelation(children, parents, relation);
|
|
1525
|
-
}
|
|
1526
|
-
async loadMorphManyForParents(parents, relation, options = {}) {
|
|
1527
|
-
if (parents.length === 0) {
|
|
1528
|
-
return indexMorphManyRelation(parents, [], relation);
|
|
1529
|
-
}
|
|
1530
|
-
const parentIds = [...new Set(parents.map((parent) => parent[relation.localKey]))];
|
|
1531
|
-
const children = await this.findWhere({
|
|
1532
|
-
[relation.morphTypeKey]: relation.morphType,
|
|
1533
|
-
[relation.morphIdKey]: parentIds
|
|
1534
|
-
}, options);
|
|
1535
|
-
return indexMorphManyRelation(parents, children, relation);
|
|
1536
|
-
}
|
|
1537
|
-
async loadMorphOneForParents(parents, relation, options = {}) {
|
|
1538
|
-
const grouped = await this.loadMorphManyForParents(parents, relation, options);
|
|
1539
|
-
const result = new Map;
|
|
1540
|
-
for (const parent of parents) {
|
|
1541
|
-
const matches = grouped.get(parent[relation.localKey]) ?? [];
|
|
1542
|
-
result.set(parent[relation.localKey], matches[0]);
|
|
1543
|
-
}
|
|
1544
|
-
return result;
|
|
1545
|
-
}
|
|
1546
|
-
async loadMorphToForChildren(children, relation, repositoriesByType, options = {}) {
|
|
1547
|
-
if (children.length === 0) {
|
|
1548
|
-
return new Map;
|
|
1549
|
-
}
|
|
1550
|
-
const idsByType = new Map;
|
|
1551
|
-
for (const child of children) {
|
|
1552
|
-
const morphType = String(child[relation.morphTypeKey]);
|
|
1553
|
-
const morphId = child[relation.morphIdKey];
|
|
1554
|
-
const ids = idsByType.get(morphType) ?? new Set;
|
|
1555
|
-
ids.add(morphId);
|
|
1556
|
-
idsByType.set(morphType, ids);
|
|
1557
|
-
}
|
|
1558
|
-
const parentsByType = new Map;
|
|
1559
|
-
for (const [morphType, ids] of idsByType) {
|
|
1560
|
-
const repository = repositoriesByType.get(morphType);
|
|
1561
|
-
if (!repository) {
|
|
1562
|
-
continue;
|
|
1563
|
-
}
|
|
1564
|
-
const ownerKey = repository.getTable().primaryKey;
|
|
1565
|
-
const parents = await repository.withConnection(this.connection).findWhere({
|
|
1566
|
-
[ownerKey]: [...ids]
|
|
1567
|
-
}, options);
|
|
1568
|
-
const indexed = new Map;
|
|
1569
|
-
for (const parent of parents) {
|
|
1570
|
-
indexed.set(parent[ownerKey], parent);
|
|
1571
|
-
}
|
|
1572
|
-
parentsByType.set(morphType, indexed);
|
|
1573
|
-
}
|
|
1574
|
-
return indexMorphToRelation(children, parentsByType, relation);
|
|
1575
|
-
}
|
|
1576
|
-
}
|
|
1577
|
-
var baseRepository_default = BaseRepository;
|
|
1578
|
-
// ../../src/core/database/connection.ts
|
|
1579
|
-
function createDatabaseConnection2(source) {
|
|
1580
|
-
return {
|
|
1581
|
-
async unsafe(query, params = []) {
|
|
1582
|
-
return await source.unsafe(query, params);
|
|
1583
|
-
}
|
|
1584
|
-
};
|
|
1585
|
-
}
|
|
1586
|
-
// ../../src/core/database/model.ts
|
|
1587
|
-
var modelRepositories = new WeakMap;
|
|
1588
|
-
var modelGlobalScopes = new WeakMap;
|
|
1589
|
-
var modelBooted = new WeakSet;
|
|
1590
|
-
function resolveModelRepository(model) {
|
|
1591
|
-
const repository = modelRepositories.get(model);
|
|
1592
|
-
if (!repository) {
|
|
1593
|
-
throw new Error(`${model.name}.repository() is not implemented.`);
|
|
1594
|
-
}
|
|
1595
|
-
return repository;
|
|
1596
|
-
}
|
|
1597
|
-
function modelStatics(model) {
|
|
1598
|
-
return model;
|
|
1599
|
-
}
|
|
1600
|
-
function ensureBooted(model) {
|
|
1601
|
-
if (modelBooted.has(model)) {
|
|
1602
|
-
return;
|
|
1603
|
-
}
|
|
1604
|
-
modelBooted.add(model);
|
|
1605
|
-
const boot = model.boot;
|
|
1606
|
-
if (typeof boot === "function") {
|
|
1607
|
-
boot.call(model);
|
|
1608
|
-
}
|
|
1609
|
-
}
|
|
1610
|
-
function getGlobalScopes(model) {
|
|
1611
|
-
return modelGlobalScopes.get(model) ?? [];
|
|
1612
|
-
}
|
|
1613
|
-
function hydrateValue(value, cast) {
|
|
1614
|
-
if (value === null || value === undefined) {
|
|
1615
|
-
return value;
|
|
1616
|
-
}
|
|
1617
|
-
switch (cast) {
|
|
1618
|
-
case "date":
|
|
1619
|
-
case "datetime":
|
|
1620
|
-
return value instanceof Date ? value : new Date(String(value));
|
|
1621
|
-
case "json":
|
|
1622
|
-
return typeof value === "string" ? JSON.parse(value) : value;
|
|
1623
|
-
case "bool":
|
|
1624
|
-
case "boolean":
|
|
1625
|
-
return value === true || value === 1 || value === "1" || value === "true";
|
|
1626
|
-
default:
|
|
1627
|
-
return value;
|
|
1628
|
-
}
|
|
1629
|
-
}
|
|
1630
|
-
function dehydrateValue(value, cast) {
|
|
1631
|
-
if (value === null || value === undefined) {
|
|
1632
|
-
return value;
|
|
1633
|
-
}
|
|
1634
|
-
switch (cast) {
|
|
1635
|
-
case "date":
|
|
1636
|
-
case "datetime":
|
|
1637
|
-
return value instanceof Date ? value : new Date(String(value));
|
|
1638
|
-
case "json":
|
|
1639
|
-
return typeof value === "string" ? value : JSON.stringify(value);
|
|
1640
|
-
case "bool":
|
|
1641
|
-
case "boolean":
|
|
1642
|
-
return Boolean(value);
|
|
1643
|
-
default:
|
|
1644
|
-
return value;
|
|
1645
|
-
}
|
|
1646
|
-
}
|
|
1647
|
-
function filterMassAssignable(fillable, guarded, input) {
|
|
1648
|
-
const resolvedGuarded = guarded ?? true;
|
|
1649
|
-
if (fillable && fillable.length > 0) {
|
|
1650
|
-
const allowed = new Set(fillable);
|
|
1651
|
-
return Object.fromEntries(Object.entries(input).filter(([key]) => allowed.has(key)));
|
|
1652
|
-
}
|
|
1653
|
-
if (resolvedGuarded === true || resolvedGuarded.includes("*")) {
|
|
1654
|
-
return {};
|
|
1655
|
-
}
|
|
1656
|
-
const blocked = new Set(resolvedGuarded);
|
|
1657
|
-
return Object.fromEntries(Object.entries(input).filter(([key]) => !blocked.has(key)));
|
|
1658
|
-
}
|
|
1659
|
-
function applyCasts(values, casts, direction) {
|
|
1660
|
-
if (Object.keys(casts).length === 0) {
|
|
1661
|
-
return values;
|
|
1662
|
-
}
|
|
1663
|
-
const result = { ...values };
|
|
1664
|
-
const castFn = direction === "hydrate" ? hydrateValue : dehydrateValue;
|
|
1665
|
-
for (const [key, cast] of Object.entries(casts)) {
|
|
1666
|
-
if (key in result && cast) {
|
|
1667
|
-
result[key] = castFn(result[key], cast);
|
|
1668
|
-
}
|
|
1669
|
-
}
|
|
1670
|
-
return result;
|
|
1671
|
-
}
|
|
1672
|
-
function applyTimestampsOnCreate(columns, values, enabled) {
|
|
1673
|
-
if (!enabled) {
|
|
1674
|
-
return values;
|
|
1675
|
-
}
|
|
1676
|
-
const now = new Date;
|
|
1677
|
-
const result = { ...values };
|
|
1678
|
-
if (columns.includes("created_at")) {
|
|
1679
|
-
result.created_at = now;
|
|
1680
|
-
}
|
|
1681
|
-
if (columns.includes("updated_at")) {
|
|
1682
|
-
result.updated_at = now;
|
|
1683
|
-
}
|
|
1684
|
-
return result;
|
|
1685
|
-
}
|
|
1686
|
-
function applyTimestampsOnUpdate(columns, values, enabled) {
|
|
1687
|
-
if (!enabled) {
|
|
1688
|
-
return values;
|
|
1689
|
-
}
|
|
1690
|
-
const result = { ...values };
|
|
1691
|
-
if (columns.includes("updated_at")) {
|
|
1692
|
-
result.updated_at = new Date;
|
|
1693
|
-
}
|
|
1694
|
-
return result;
|
|
1695
|
-
}
|
|
1696
|
-
|
|
1697
|
-
class Model {
|
|
1698
|
-
attributes;
|
|
1699
|
-
repository;
|
|
1700
|
-
static $fillable;
|
|
1701
|
-
static $guarded;
|
|
1702
|
-
static $casts = {};
|
|
1703
|
-
static $timestamps = true;
|
|
1704
|
-
_exists;
|
|
1705
|
-
constructor(attributes, repository, exists = true) {
|
|
1706
|
-
this.attributes = attributes;
|
|
1707
|
-
this.repository = repository;
|
|
1708
|
-
this._exists = exists;
|
|
1709
|
-
}
|
|
1710
|
-
get $exists() {
|
|
1711
|
-
return this._exists;
|
|
1712
|
-
}
|
|
1713
|
-
get(key) {
|
|
1714
|
-
return this.attributes[key];
|
|
1715
|
-
}
|
|
1716
|
-
get id() {
|
|
1717
|
-
return this.attributes[this.primaryKey()];
|
|
1718
|
-
}
|
|
1719
|
-
toObject() {
|
|
1720
|
-
return { ...this.attributes };
|
|
1721
|
-
}
|
|
1722
|
-
primaryKey() {
|
|
1723
|
-
throw new Error(`${this.constructor.name}.primaryKey() is not implemented.`);
|
|
1724
|
-
}
|
|
1725
|
-
static primaryKeyField() {
|
|
1726
|
-
return resolveModelRepository(this).getTable().primaryKey;
|
|
1727
|
-
}
|
|
1728
|
-
static hydrateAttributes(attributes) {
|
|
1729
|
-
const casts = modelStatics(this).$casts ?? {};
|
|
1730
|
-
return applyCasts(attributes, casts, "hydrate");
|
|
1731
|
-
}
|
|
1732
|
-
static dehydrateAttributes(attributes) {
|
|
1733
|
-
const casts = modelStatics(this).$casts ?? {};
|
|
1734
|
-
return applyCasts(attributes, casts, "dehydrate");
|
|
1735
|
-
}
|
|
1736
|
-
static fromRecord(record, repository, exists = true) {
|
|
1737
|
-
const statics = modelStatics(this);
|
|
1738
|
-
const hydrated = statics.hydrateAttributes(record);
|
|
1739
|
-
return new statics(hydrated, repository, exists);
|
|
1740
|
-
}
|
|
1741
|
-
static boot() {}
|
|
1742
|
-
static addGlobalScope(_name, scope) {
|
|
1743
|
-
ensureBooted(this);
|
|
1744
|
-
const existing = modelGlobalScopes.get(this) ?? [];
|
|
1745
|
-
modelGlobalScopes.set(this, [
|
|
1746
|
-
...existing,
|
|
1747
|
-
scope
|
|
1748
|
-
]);
|
|
1749
|
-
}
|
|
1750
|
-
static repository() {
|
|
1751
|
-
return resolveModelRepository(this);
|
|
1752
|
-
}
|
|
1753
|
-
static query() {
|
|
1754
|
-
ensureBooted(this);
|
|
1755
|
-
const repository = resolveModelRepository(this);
|
|
1756
|
-
let query = repository.query();
|
|
1757
|
-
for (const scope of getGlobalScopes(this)) {
|
|
1758
|
-
query = scope(query);
|
|
1759
|
-
}
|
|
1760
|
-
return query;
|
|
1761
|
-
}
|
|
1762
|
-
static async create(attributes) {
|
|
1763
|
-
const statics = modelStatics(this);
|
|
1764
|
-
ensureBooted(this);
|
|
1765
|
-
const repository = resolveModelRepository(this);
|
|
1766
|
-
const table = repository.getTable();
|
|
1767
|
-
const timestamps = statics.$timestamps ?? true;
|
|
1768
|
-
const assignable = filterMassAssignable(statics.$fillable, statics.$guarded, attributes);
|
|
1769
|
-
const withTimestamps = applyTimestampsOnCreate(table.columns, assignable, timestamps);
|
|
1770
|
-
const payload = statics.dehydrateAttributes(withTimestamps);
|
|
1771
|
-
const record = await repository.create(payload);
|
|
1772
|
-
return statics.fromRecord(record, repository, true);
|
|
1773
|
-
}
|
|
1774
|
-
static async find(id) {
|
|
1775
|
-
const statics = modelStatics(this);
|
|
1776
|
-
const repository = resolveModelRepository(this);
|
|
1777
|
-
const primaryKey = repository.getTable().primaryKey;
|
|
1778
|
-
const record = await Model.query.call(this).where({ [primaryKey]: id }).first();
|
|
1779
|
-
return record ? statics.fromRecord(record, repository, true) : null;
|
|
1780
|
-
}
|
|
1781
|
-
static async findOrFail(id, errorFactory) {
|
|
1782
|
-
const model = await Model.find.call(this, id);
|
|
1783
|
-
if (model) {
|
|
1784
|
-
return model;
|
|
1785
|
-
}
|
|
1786
|
-
throw errorFactory?.(id) ?? new NotFoundError(`${this.name} ${String(id)} not found.`);
|
|
1787
|
-
}
|
|
1788
|
-
static async all(options = {}) {
|
|
1789
|
-
const statics = modelStatics(this);
|
|
1790
|
-
const repository = resolveModelRepository(this);
|
|
1791
|
-
let query = Model.query.call(this);
|
|
1792
|
-
if (options.orderBy) {
|
|
1793
|
-
query = query.orderBy(options.orderBy);
|
|
1794
|
-
}
|
|
1795
|
-
if (options.limit !== undefined) {
|
|
1796
|
-
query = query.limit(options.limit);
|
|
1797
|
-
}
|
|
1798
|
-
const rows = await query.get();
|
|
1799
|
-
return rows.map((row) => statics.fromRecord(row, repository, true));
|
|
1800
|
-
}
|
|
1801
|
-
static async firstWhere(where, options = {}) {
|
|
1802
|
-
const statics = modelStatics(this);
|
|
1803
|
-
const repository = resolveModelRepository(this);
|
|
1804
|
-
let query = Model.query.call(this).where(where);
|
|
1805
|
-
if (options.orderBy) {
|
|
1806
|
-
query = query.orderBy(options.orderBy);
|
|
1807
|
-
}
|
|
1808
|
-
const record = await query.first();
|
|
1809
|
-
return record ? statics.fromRecord(record, repository, true) : null;
|
|
1810
|
-
}
|
|
1811
|
-
async save() {
|
|
1812
|
-
const ModelClass = modelStatics(this.constructor);
|
|
1813
|
-
const timestamps = ModelClass.$timestamps ?? true;
|
|
1814
|
-
const casts = ModelClass.$casts ?? {};
|
|
1815
|
-
const table = this.repository.getTable();
|
|
1816
|
-
if (this.$exists) {
|
|
1817
|
-
const changes = applyTimestampsOnUpdate(table.columns, applyCasts(this.attributes, casts, "dehydrate"), timestamps);
|
|
1818
|
-
const record2 = await this.repository.updateByIdOrThrow(this.id, changes);
|
|
1819
|
-
this.attributes = ModelClass.hydrateAttributes(record2);
|
|
1820
|
-
return this;
|
|
1821
|
-
}
|
|
1822
|
-
const assignable = filterMassAssignable(ModelClass.$fillable, ModelClass.$guarded, this.attributes);
|
|
1823
|
-
const withTimestamps = applyTimestampsOnCreate(table.columns, assignable, timestamps);
|
|
1824
|
-
const payload = ModelClass.dehydrateAttributes(withTimestamps);
|
|
1825
|
-
const record = await this.repository.create(payload);
|
|
1826
|
-
this.attributes = ModelClass.hydrateAttributes(record);
|
|
1827
|
-
this._exists = true;
|
|
1828
|
-
return this;
|
|
1829
|
-
}
|
|
1830
|
-
async update(changes) {
|
|
1831
|
-
const ModelClass = modelStatics(this.constructor);
|
|
1832
|
-
const assignable = filterMassAssignable(ModelClass.$fillable, ModelClass.$guarded, changes);
|
|
1833
|
-
Object.assign(this.attributes, assignable);
|
|
1834
|
-
return await this.save();
|
|
1835
|
-
}
|
|
1836
|
-
async delete() {
|
|
1837
|
-
if (resolveSoftDeleteColumn(this.repository.getTable())) {
|
|
1838
|
-
return await this.repository.deleteById(this.id);
|
|
1839
|
-
}
|
|
1840
|
-
return await this.repository.forceDeleteById(this.id);
|
|
1841
|
-
}
|
|
1842
|
-
async forceDelete() {
|
|
1843
|
-
return await this.repository.forceDeleteById(this.id);
|
|
1844
|
-
}
|
|
1845
|
-
async restore() {
|
|
1846
|
-
const ModelClass = modelStatics(this.constructor);
|
|
1847
|
-
const record = await this.repository.restoreById(this.id);
|
|
1848
|
-
if (!record) {
|
|
1849
|
-
return null;
|
|
1850
|
-
}
|
|
1851
|
-
this.attributes = ModelClass.hydrateAttributes(record);
|
|
1852
|
-
return this;
|
|
1853
|
-
}
|
|
1854
|
-
async loadHasMany(as, relation, childRepository, options = {}) {
|
|
1855
|
-
const grouped = await childRepository.withConnection(this.repository.getConnection()).loadHasManyForParents([this.attributes], relation, options);
|
|
1856
|
-
const loaded = grouped.get(this.attributes[relation.localKey]) ?? [];
|
|
1857
|
-
return Object.assign(this, { [as]: loaded });
|
|
1858
|
-
}
|
|
1859
|
-
async loadHasOne(as, relation, childRepository, options = {}) {
|
|
1860
|
-
const loaded = await this.loadHasMany(as, relation, childRepository, { ...options, limit: 1 });
|
|
1861
|
-
const value = loaded[as]?.[0];
|
|
1862
|
-
return Object.assign(this, { [as]: value });
|
|
1863
|
-
}
|
|
1864
|
-
async loadBelongsTo(as, relation, parentRepository, options = {}) {
|
|
1865
|
-
const grouped = await this.repository.loadBelongsToForParents([this.attributes], relation, parentRepository, options);
|
|
1866
|
-
const loaded = grouped.get(this.attributes[relation.foreignKey]);
|
|
1867
|
-
return Object.assign(this, { [as]: loaded });
|
|
1868
|
-
}
|
|
1869
|
-
async loadBelongsToMany(as, relation, relatedRepository, options = {}) {
|
|
1870
|
-
const connection = this.repository.getConnection();
|
|
1871
|
-
const parentId = this.attributes[relation.parentKey];
|
|
1872
|
-
const pivotRows = await connection.unsafe(`SELECT * FROM ${relation.pivotTable} WHERE ${String(relation.foreignPivotKey)} = $1`, [parentId]);
|
|
1873
|
-
if (pivotRows.length === 0) {
|
|
1874
|
-
return Object.assign(this, { [as]: [] });
|
|
1875
|
-
}
|
|
1876
|
-
const relatedIds = [
|
|
1877
|
-
...new Set(pivotRows.map((row) => row[relation.relatedPivotKey]))
|
|
1878
|
-
];
|
|
1879
|
-
const relatedRows = await relatedRepository.withConnection(connection).findAll({
|
|
1880
|
-
...options,
|
|
1881
|
-
where: {
|
|
1882
|
-
[relation.relatedKey]: relatedIds
|
|
1883
|
-
}
|
|
1884
|
-
});
|
|
1885
|
-
const grouped = indexBelongsToManyRelation([this.attributes], pivotRows, relatedRows, relation);
|
|
1886
|
-
const loaded = grouped.get(parentId) ?? [];
|
|
1887
|
-
return Object.assign(this, { [as]: loaded });
|
|
1888
|
-
}
|
|
1889
|
-
mergeAttributes(patch) {
|
|
1890
|
-
Object.assign(this.attributes, patch);
|
|
1891
|
-
return this;
|
|
1892
|
-
}
|
|
1893
|
-
}
|
|
1894
|
-
function registerModelRepository(model, repository) {
|
|
1895
|
-
modelRepositories.set(model, repository);
|
|
1896
|
-
ensureBooted(model);
|
|
1897
|
-
return model;
|
|
1898
|
-
}
|
|
1899
|
-
// ../../src/core/database/schema/columnDefinition.ts
|
|
1900
|
-
class ColumnDefinition {
|
|
1901
|
-
name;
|
|
1902
|
-
kind;
|
|
1903
|
-
length;
|
|
1904
|
-
isNullable = false;
|
|
1905
|
-
isPrimary = false;
|
|
1906
|
-
isUnique = false;
|
|
1907
|
-
autoIncrement = false;
|
|
1908
|
-
defaultValue;
|
|
1909
|
-
checkExpression;
|
|
1910
|
-
foreignKey;
|
|
1911
|
-
constructor(name, kind) {
|
|
1912
|
-
this.name = name;
|
|
1913
|
-
this.kind = kind;
|
|
1914
|
-
}
|
|
1915
|
-
nullable() {
|
|
1916
|
-
this.isNullable = true;
|
|
1917
|
-
return this;
|
|
1918
|
-
}
|
|
1919
|
-
notNullable() {
|
|
1920
|
-
this.isNullable = false;
|
|
1921
|
-
return this;
|
|
1922
|
-
}
|
|
1923
|
-
default(value) {
|
|
1924
|
-
if (typeof value === "boolean") {
|
|
1925
|
-
this.defaultValue = value ? "TRUE" : "FALSE";
|
|
1926
|
-
return this;
|
|
1927
|
-
}
|
|
1928
|
-
if (typeof value === "number") {
|
|
1929
|
-
this.defaultValue = String(value);
|
|
1930
|
-
return this;
|
|
1931
|
-
}
|
|
1932
|
-
this.defaultValue = `'${value.replace(/'/g, "''")}'`;
|
|
1933
|
-
return this;
|
|
1934
|
-
}
|
|
1935
|
-
defaultRaw(expression) {
|
|
1936
|
-
this.defaultValue = expression;
|
|
1937
|
-
return this;
|
|
1938
|
-
}
|
|
1939
|
-
unique() {
|
|
1940
|
-
this.isUnique = true;
|
|
1941
|
-
return this;
|
|
1942
|
-
}
|
|
1943
|
-
primary() {
|
|
1944
|
-
this.isPrimary = true;
|
|
1945
|
-
return this;
|
|
1946
|
-
}
|
|
1947
|
-
check(expression) {
|
|
1948
|
-
this.checkExpression = expression;
|
|
1949
|
-
return this;
|
|
1950
|
-
}
|
|
1951
|
-
}
|
|
1952
|
-
|
|
1953
|
-
class ForeignIdColumnDefinition extends ColumnDefinition {
|
|
1954
|
-
constructor(name) {
|
|
1955
|
-
super(name, "foreignId");
|
|
1956
|
-
this.notNullable();
|
|
1957
|
-
}
|
|
1958
|
-
references(table, column = "id") {
|
|
1959
|
-
this.foreignKey = {
|
|
1960
|
-
referencesTable: table,
|
|
1961
|
-
referencesColumn: column
|
|
1962
|
-
};
|
|
1963
|
-
return this;
|
|
1964
|
-
}
|
|
1965
|
-
constrained(table) {
|
|
1966
|
-
const referencesTable = table ?? inferReferencedTable(this.name);
|
|
1967
|
-
return this.references(referencesTable);
|
|
1968
|
-
}
|
|
1969
|
-
cascadeOnDelete() {
|
|
1970
|
-
if (!this.foreignKey) {
|
|
1971
|
-
throw new Error(`Foreign key is not defined for column ${this.name}`);
|
|
1972
|
-
}
|
|
1973
|
-
this.foreignKey.onDelete = "cascade";
|
|
1974
|
-
return this;
|
|
1975
|
-
}
|
|
1976
|
-
nullOnDelete() {
|
|
1977
|
-
if (!this.foreignKey) {
|
|
1978
|
-
throw new Error(`Foreign key is not defined for column ${this.name}`);
|
|
1979
|
-
}
|
|
1980
|
-
this.foreignKey.onDelete = "set null";
|
|
1981
|
-
return this;
|
|
1982
|
-
}
|
|
1983
|
-
}
|
|
1984
|
-
function inferReferencedTable(columnName) {
|
|
1985
|
-
if (!columnName.endsWith("_id")) {
|
|
1986
|
-
throw new Error(`Cannot infer referenced table from column ${columnName}`);
|
|
1987
|
-
}
|
|
1988
|
-
return columnName.slice(0, -3);
|
|
1989
|
-
}
|
|
1990
|
-
|
|
1991
|
-
// ../../src/core/database/schema/blueprint.ts
|
|
1992
|
-
class Blueprint {
|
|
1993
|
-
table;
|
|
1994
|
-
action;
|
|
1995
|
-
columns = [];
|
|
1996
|
-
indexes = [];
|
|
1997
|
-
droppedColumns = [];
|
|
1998
|
-
droppedIndexes = [];
|
|
1999
|
-
constructor(table, action) {
|
|
2000
|
-
this.table = table;
|
|
2001
|
-
this.action = action;
|
|
2002
|
-
}
|
|
2003
|
-
id(name = "id") {
|
|
2004
|
-
const column = new ColumnDefinition(name, "id");
|
|
2005
|
-
column.primary();
|
|
2006
|
-
column.autoIncrement = true;
|
|
2007
|
-
this.columns.push(column);
|
|
2008
|
-
return column;
|
|
2009
|
-
}
|
|
2010
|
-
string(name, length) {
|
|
2011
|
-
const column = new ColumnDefinition(name, "string");
|
|
2012
|
-
column.length = length;
|
|
2013
|
-
column.notNullable();
|
|
2014
|
-
this.columns.push(column);
|
|
2015
|
-
return column;
|
|
2016
|
-
}
|
|
2017
|
-
text(name) {
|
|
2018
|
-
const column = new ColumnDefinition(name, "text");
|
|
2019
|
-
column.notNullable();
|
|
2020
|
-
this.columns.push(column);
|
|
2021
|
-
return column;
|
|
2022
|
-
}
|
|
2023
|
-
boolean(name) {
|
|
2024
|
-
const column = new ColumnDefinition(name, "boolean");
|
|
2025
|
-
column.notNullable();
|
|
2026
|
-
this.columns.push(column);
|
|
2027
|
-
return column;
|
|
2028
|
-
}
|
|
2029
|
-
integer(name) {
|
|
2030
|
-
const column = new ColumnDefinition(name, "integer");
|
|
2031
|
-
column.notNullable();
|
|
2032
|
-
this.columns.push(column);
|
|
2033
|
-
return column;
|
|
2034
|
-
}
|
|
2035
|
-
bigInteger(name) {
|
|
2036
|
-
const column = new ColumnDefinition(name, "bigInteger");
|
|
2037
|
-
column.notNullable();
|
|
2038
|
-
this.columns.push(column);
|
|
2039
|
-
return column;
|
|
2040
|
-
}
|
|
2041
|
-
timestamp(name) {
|
|
2042
|
-
const column = new ColumnDefinition(name, "timestamp");
|
|
2043
|
-
column.notNullable();
|
|
2044
|
-
this.columns.push(column);
|
|
2045
|
-
return column;
|
|
2046
|
-
}
|
|
2047
|
-
json(name) {
|
|
2048
|
-
const column = new ColumnDefinition(name, "json");
|
|
2049
|
-
column.notNullable();
|
|
2050
|
-
this.columns.push(column);
|
|
2051
|
-
return column;
|
|
2052
|
-
}
|
|
2053
|
-
jsonb(name) {
|
|
2054
|
-
const column = new ColumnDefinition(name, "jsonb");
|
|
2055
|
-
column.notNullable();
|
|
2056
|
-
this.columns.push(column);
|
|
2057
|
-
return column;
|
|
2058
|
-
}
|
|
2059
|
-
foreignId(name) {
|
|
2060
|
-
const column = new ForeignIdColumnDefinition(name);
|
|
2061
|
-
this.columns.push(column);
|
|
2062
|
-
return column;
|
|
2063
|
-
}
|
|
2064
|
-
timestamps() {
|
|
2065
|
-
this.timestamp("created_at").defaultRaw("NOW()");
|
|
2066
|
-
this.timestamp("updated_at").defaultRaw("NOW()");
|
|
2067
|
-
}
|
|
2068
|
-
softDeletes() {
|
|
2069
|
-
this.timestamp("deleted_at").nullable();
|
|
2070
|
-
}
|
|
2071
|
-
dropColumn(name) {
|
|
2072
|
-
this.droppedColumns.push(name);
|
|
2073
|
-
}
|
|
2074
|
-
dropSoftDeletes() {
|
|
2075
|
-
this.dropColumn("deleted_at");
|
|
2076
|
-
this.dropIndex(`idx_${this.table}_deleted_at`);
|
|
2077
|
-
}
|
|
2078
|
-
dropIndex(name) {
|
|
2079
|
-
this.droppedIndexes.push(name);
|
|
2080
|
-
}
|
|
2081
|
-
unique(columns, name) {
|
|
2082
|
-
this.indexes.push({
|
|
2083
|
-
name,
|
|
2084
|
-
columns: Array.isArray(columns) ? columns : [columns],
|
|
2085
|
-
kind: "unique"
|
|
2086
|
-
});
|
|
2087
|
-
}
|
|
2088
|
-
index(columns, options = {}) {
|
|
2089
|
-
this.indexes.push({
|
|
2090
|
-
name: options.name,
|
|
2091
|
-
columns: Array.isArray(columns) ? columns : [columns],
|
|
2092
|
-
kind: "index",
|
|
2093
|
-
order: options.order
|
|
2094
|
-
});
|
|
2095
|
-
}
|
|
2096
|
-
partialIndex(columns, where, nameOrOptions) {
|
|
2097
|
-
const options = typeof nameOrOptions === "string" ? { name: nameOrOptions } : nameOrOptions ?? {};
|
|
2098
|
-
this.indexes.push({
|
|
2099
|
-
name: options.name,
|
|
2100
|
-
columns: Array.isArray(columns) ? columns : [columns],
|
|
2101
|
-
kind: options.unique ? "uniquePartial" : "partial",
|
|
2102
|
-
where
|
|
2103
|
-
});
|
|
2104
|
-
}
|
|
2105
|
-
fullText(columns, name) {
|
|
2106
|
-
this.indexes.push({
|
|
2107
|
-
name,
|
|
2108
|
-
columns: Array.isArray(columns) ? columns : [columns],
|
|
2109
|
-
kind: "fullText"
|
|
2110
|
-
});
|
|
2111
|
-
}
|
|
2112
|
-
ginIndex(column, name) {
|
|
2113
|
-
this.indexes.push({
|
|
2114
|
-
name,
|
|
2115
|
-
columns: [column],
|
|
2116
|
-
kind: "gin"
|
|
2117
|
-
});
|
|
2118
|
-
}
|
|
2119
|
-
}
|
|
2120
|
-
// ../../src/core/database/schema/driver.ts
|
|
2121
|
-
function normalizeConnectionName(connection) {
|
|
2122
|
-
const normalized = connection.trim().toLowerCase();
|
|
2123
|
-
if (normalized === "pgsql" || normalized === "postgres" || normalized === "postgresql") {
|
|
2124
|
-
return "pgsql";
|
|
2125
|
-
}
|
|
2126
|
-
if (normalized === "mysql" || normalized === "mariadb") {
|
|
2127
|
-
return "mysql";
|
|
2128
|
-
}
|
|
2129
|
-
if (normalized === "sqlite") {
|
|
2130
|
-
return "sqlite";
|
|
2131
|
-
}
|
|
2132
|
-
throw new Error(`Unsupported DB_CONNECTION: ${connection}`);
|
|
2133
|
-
}
|
|
2134
|
-
function resolveDriverFromUrl(url) {
|
|
2135
|
-
const normalized = url.trim().toLowerCase();
|
|
2136
|
-
if (normalized.startsWith("postgres://") || normalized.startsWith("postgresql://") || normalized.startsWith("postgres:")) {
|
|
2137
|
-
return "pgsql";
|
|
2138
|
-
}
|
|
2139
|
-
if (normalized.startsWith("mysql://") || normalized.startsWith("mysql:")) {
|
|
2140
|
-
return "mysql";
|
|
2141
|
-
}
|
|
2142
|
-
if (normalized.startsWith("sqlite:")) {
|
|
2143
|
-
return "sqlite";
|
|
2144
|
-
}
|
|
2145
|
-
return null;
|
|
2146
|
-
}
|
|
2147
|
-
function resolveDatabaseDriver(options = {}) {
|
|
2148
|
-
const connection = options.connection ?? process.env.DB_CONNECTION;
|
|
2149
|
-
if (connection) {
|
|
2150
|
-
return normalizeConnectionName(connection);
|
|
2151
|
-
}
|
|
2152
|
-
const url = options.url ?? process.env.DATABASE_URL ?? "";
|
|
2153
|
-
const fromUrl = resolveDriverFromUrl(url);
|
|
2154
|
-
if (fromUrl) {
|
|
2155
|
-
return fromUrl;
|
|
2156
|
-
}
|
|
2157
|
-
return "pgsql";
|
|
2158
|
-
}
|
|
2159
|
-
// ../../src/core/database/schema/errors.ts
|
|
2160
|
-
class UnsupportedSchemaFeatureError extends Error {
|
|
2161
|
-
constructor(feature, driver) {
|
|
2162
|
-
super(`${feature} is not supported for the ${driver} driver`);
|
|
2163
|
-
this.name = "UnsupportedSchemaFeatureError";
|
|
2164
|
-
}
|
|
2165
|
-
}
|
|
2166
|
-
// ../../src/core/database/schema/grammars/grammar.ts
|
|
2167
|
-
function compileColumnType(driver, column) {
|
|
2168
|
-
switch (column.kind) {
|
|
2169
|
-
case "id":
|
|
2170
|
-
return compileIdType(driver);
|
|
2171
|
-
case "string":
|
|
2172
|
-
return compileStringType(driver, column.length);
|
|
2173
|
-
case "text":
|
|
2174
|
-
return compileTextType(driver);
|
|
2175
|
-
case "boolean":
|
|
2176
|
-
return compileBooleanType(driver);
|
|
2177
|
-
case "integer":
|
|
2178
|
-
case "foreignId":
|
|
2179
|
-
return compileIntegerType(driver);
|
|
2180
|
-
case "bigInteger":
|
|
2181
|
-
return compileBigIntegerType(driver);
|
|
2182
|
-
case "timestamp":
|
|
2183
|
-
return compileTimestampType(driver);
|
|
2184
|
-
case "json":
|
|
2185
|
-
return compileJsonType(driver);
|
|
2186
|
-
case "jsonb":
|
|
2187
|
-
return compileJsonbType(driver);
|
|
2188
|
-
default:
|
|
2189
|
-
throw new Error(`Unsupported column kind: ${column.kind}`);
|
|
2190
|
-
}
|
|
2191
|
-
}
|
|
2192
|
-
function compileIdType(driver) {
|
|
2193
|
-
switch (driver) {
|
|
2194
|
-
case "pgsql":
|
|
2195
|
-
return "SERIAL";
|
|
2196
|
-
case "mysql":
|
|
2197
|
-
return "BIGINT UNSIGNED";
|
|
2198
|
-
case "sqlite":
|
|
2199
|
-
return "INTEGER";
|
|
2200
|
-
}
|
|
2201
|
-
}
|
|
2202
|
-
function compileStringType(driver, length) {
|
|
2203
|
-
switch (driver) {
|
|
2204
|
-
case "pgsql":
|
|
2205
|
-
return "TEXT";
|
|
2206
|
-
case "mysql":
|
|
2207
|
-
return length ? `VARCHAR(${length})` : "VARCHAR(255)";
|
|
2208
|
-
case "sqlite":
|
|
2209
|
-
return "TEXT";
|
|
2210
|
-
}
|
|
2211
|
-
}
|
|
2212
|
-
function compileTextType(driver) {
|
|
2213
|
-
switch (driver) {
|
|
2214
|
-
case "pgsql":
|
|
2215
|
-
case "sqlite":
|
|
2216
|
-
return "TEXT";
|
|
2217
|
-
case "mysql":
|
|
2218
|
-
return "TEXT";
|
|
2219
|
-
}
|
|
2220
|
-
}
|
|
2221
|
-
function compileBooleanType(driver) {
|
|
2222
|
-
switch (driver) {
|
|
2223
|
-
case "pgsql":
|
|
2224
|
-
return "BOOLEAN";
|
|
2225
|
-
case "mysql":
|
|
2226
|
-
return "BOOLEAN";
|
|
2227
|
-
case "sqlite":
|
|
2228
|
-
return "INTEGER";
|
|
2229
|
-
}
|
|
2230
|
-
}
|
|
2231
|
-
function compileIntegerType(driver) {
|
|
2232
|
-
switch (driver) {
|
|
2233
|
-
case "pgsql":
|
|
2234
|
-
return "INTEGER";
|
|
2235
|
-
case "mysql":
|
|
2236
|
-
return "INT";
|
|
2237
|
-
case "sqlite":
|
|
2238
|
-
return "INTEGER";
|
|
2239
|
-
}
|
|
2240
|
-
}
|
|
2241
|
-
function compileBigIntegerType(driver) {
|
|
2242
|
-
switch (driver) {
|
|
2243
|
-
case "pgsql":
|
|
2244
|
-
return "BIGINT";
|
|
2245
|
-
case "mysql":
|
|
2246
|
-
return "BIGINT";
|
|
2247
|
-
case "sqlite":
|
|
2248
|
-
return "INTEGER";
|
|
2249
|
-
}
|
|
2250
|
-
}
|
|
2251
|
-
function compileTimestampType(driver) {
|
|
2252
|
-
switch (driver) {
|
|
2253
|
-
case "pgsql":
|
|
2254
|
-
return "TIMESTAMPTZ";
|
|
2255
|
-
case "mysql":
|
|
2256
|
-
return "TIMESTAMP";
|
|
2257
|
-
case "sqlite":
|
|
2258
|
-
return "TEXT";
|
|
2259
|
-
}
|
|
2260
|
-
}
|
|
2261
|
-
function compileJsonType(driver) {
|
|
2262
|
-
switch (driver) {
|
|
2263
|
-
case "pgsql":
|
|
2264
|
-
return "JSONB";
|
|
2265
|
-
case "mysql":
|
|
2266
|
-
return "JSON";
|
|
2267
|
-
case "sqlite":
|
|
2268
|
-
return "TEXT";
|
|
2269
|
-
}
|
|
2270
|
-
}
|
|
2271
|
-
function compileJsonbType(driver) {
|
|
2272
|
-
switch (driver) {
|
|
2273
|
-
case "pgsql":
|
|
2274
|
-
return "JSONB";
|
|
2275
|
-
case "mysql":
|
|
2276
|
-
return "JSON";
|
|
2277
|
-
case "sqlite":
|
|
2278
|
-
return "TEXT";
|
|
2279
|
-
}
|
|
2280
|
-
}
|
|
2281
|
-
|
|
2282
|
-
// ../../src/core/database/schema/grammars/compileStatements.ts
|
|
2283
|
-
function compileCreateTable(driver, blueprint) {
|
|
2284
|
-
const table = quoteIdentifier(blueprint.table);
|
|
2285
|
-
const parts = blueprint.columns.map((column) => compileColumn(driver, column, "create"));
|
|
2286
|
-
for (const index of blueprint.indexes) {
|
|
2287
|
-
if (index.kind === "unique" && index.columns.length > 1) {
|
|
2288
|
-
const columns = index.columns.map((column) => quoteIdentifier(column)).join(", ");
|
|
2289
|
-
parts.push(`UNIQUE (${columns})`);
|
|
2290
|
-
}
|
|
2291
|
-
}
|
|
2292
|
-
const statements = [`CREATE TABLE IF NOT EXISTS ${table} (
|
|
2293
|
-
${parts.join(`,
|
|
2294
|
-
`)}
|
|
2295
|
-
)`];
|
|
2296
|
-
for (const index of blueprint.indexes) {
|
|
2297
|
-
if (index.kind === "unique" && index.columns.length === 1) {
|
|
2298
|
-
continue;
|
|
2299
|
-
}
|
|
2300
|
-
if (index.kind === "index") {
|
|
2301
|
-
statements.push(compileIndex(driver, blueprint.table, index));
|
|
2302
|
-
} else if (index.kind === "partial" || index.kind === "uniquePartial" || index.kind === "gin" || index.kind === "fullText") {
|
|
2303
|
-
statements.push(...compileSpecialIndex(driver, blueprint.table, index));
|
|
2304
|
-
}
|
|
2305
|
-
}
|
|
2306
|
-
return statements;
|
|
2307
|
-
}
|
|
2308
|
-
function compileAlterTable(driver, blueprint) {
|
|
2309
|
-
const statements = [];
|
|
2310
|
-
const table = quoteIdentifier(blueprint.table);
|
|
2311
|
-
for (const column of blueprint.columns) {
|
|
2312
|
-
const addPrefix = driver === "pgsql" ? "ADD COLUMN IF NOT EXISTS" : "ADD COLUMN";
|
|
2313
|
-
statements.push(`ALTER TABLE ${table}
|
|
2314
|
-
${addPrefix} ${compileColumn(driver, column, "alter")}`);
|
|
2315
|
-
}
|
|
2316
|
-
for (const columnName of blueprint.droppedColumns) {
|
|
2317
|
-
const dropPrefix = driver === "pgsql" ? "DROP COLUMN IF EXISTS" : "DROP COLUMN";
|
|
2318
|
-
statements.push(`ALTER TABLE ${table} ${dropPrefix} ${quoteIdentifier(columnName)}`);
|
|
2319
|
-
}
|
|
2320
|
-
for (const indexName of blueprint.droppedIndexes) {
|
|
2321
|
-
statements.push(`DROP INDEX IF EXISTS ${quoteIdentifier(indexName)}`);
|
|
2322
|
-
}
|
|
2323
|
-
for (const index of blueprint.indexes) {
|
|
2324
|
-
if (index.kind === "index" || index.kind === "unique") {
|
|
2325
|
-
statements.push(compileIndex(driver, blueprint.table, index));
|
|
2326
|
-
} else {
|
|
2327
|
-
statements.push(...compileSpecialIndex(driver, blueprint.table, index));
|
|
2328
|
-
}
|
|
2329
|
-
}
|
|
2330
|
-
return statements;
|
|
2331
|
-
}
|
|
2332
|
-
function compileDropTable(driver, tableName) {
|
|
2333
|
-
const cascade = driver === "pgsql" ? " CASCADE" : "";
|
|
2334
|
-
return [`DROP TABLE IF EXISTS ${quoteIdentifier(tableName)}${cascade}`];
|
|
2335
|
-
}
|
|
2336
|
-
function compileColumn(driver, column, mode) {
|
|
2337
|
-
const parts = [quoteIdentifier(column.name), compileColumnType(driver, column)];
|
|
2338
|
-
if (column.autoIncrement && driver === "mysql") {
|
|
2339
|
-
parts[1] = `${parts[1]} AUTO_INCREMENT`;
|
|
2340
|
-
}
|
|
2341
|
-
if (column.isPrimary && mode === "create") {
|
|
2342
|
-
if (driver === "sqlite") {
|
|
2343
|
-
parts.push("PRIMARY KEY AUTOINCREMENT");
|
|
2344
|
-
} else {
|
|
2345
|
-
parts.push("PRIMARY KEY");
|
|
2346
|
-
}
|
|
2347
|
-
} else if (!column.isNullable) {
|
|
2348
|
-
parts.push("NOT NULL");
|
|
2349
|
-
} else if (column.isNullable) {
|
|
2350
|
-
parts.push("NULL");
|
|
2351
|
-
}
|
|
2352
|
-
if (column.defaultValue !== undefined) {
|
|
2353
|
-
parts.push(`DEFAULT ${column.defaultValue}`);
|
|
2354
|
-
}
|
|
2355
|
-
if (column.isUnique) {
|
|
2356
|
-
parts.push("UNIQUE");
|
|
2357
|
-
}
|
|
2358
|
-
if (column.checkExpression) {
|
|
2359
|
-
parts.push(`CHECK (${column.checkExpression})`);
|
|
2360
|
-
}
|
|
2361
|
-
if (column.foreignKey) {
|
|
2362
|
-
const { referencesTable, referencesColumn, onDelete } = column.foreignKey;
|
|
2363
|
-
const reference = `${quoteIdentifier(referencesTable)}(${quoteIdentifier(referencesColumn)})`;
|
|
2364
|
-
let clause = `REFERENCES ${reference}`;
|
|
2365
|
-
if (onDelete === "cascade") {
|
|
2366
|
-
clause += " ON DELETE CASCADE";
|
|
2367
|
-
} else if (onDelete === "set null") {
|
|
2368
|
-
clause += " ON DELETE SET NULL";
|
|
2369
|
-
}
|
|
2370
|
-
parts.push(clause);
|
|
2371
|
-
}
|
|
2372
|
-
return parts.join(" ");
|
|
2373
|
-
}
|
|
2374
|
-
function compileIndex(_driver, tableName, index) {
|
|
2375
|
-
const indexName = index.name ?? defaultIndexName(tableName, index.columns, index.kind === "unique" ? "unique" : "index");
|
|
2376
|
-
const columns = index.columns.map((column) => {
|
|
2377
|
-
const quoted = quoteIdentifier(column);
|
|
2378
|
-
if (index.order === "desc") {
|
|
2379
|
-
return `${quoted} DESC`;
|
|
2380
|
-
}
|
|
2381
|
-
return quoted;
|
|
2382
|
-
}).join(", ");
|
|
2383
|
-
const unique = index.kind === "unique" ? "UNIQUE " : "";
|
|
2384
|
-
return `CREATE ${unique}INDEX IF NOT EXISTS ${quoteIdentifier(indexName)} ON ${quoteIdentifier(tableName)}(${columns})`;
|
|
2385
|
-
}
|
|
2386
|
-
function compileSpecialIndex(driver, tableName, index) {
|
|
2387
|
-
const indexName = index.name ?? defaultIndexName(tableName, index.columns, index.kind);
|
|
2388
|
-
const columns = index.columns.map((column) => quoteIdentifier(column)).join(", ");
|
|
2389
|
-
switch (index.kind) {
|
|
2390
|
-
case "partial":
|
|
2391
|
-
case "uniquePartial": {
|
|
2392
|
-
if (driver !== "pgsql") {
|
|
2393
|
-
throw new UnsupportedSchemaFeatureError("partialIndex()", driver);
|
|
2394
|
-
}
|
|
2395
|
-
const unique = index.kind === "uniquePartial" ? "UNIQUE " : "";
|
|
2396
|
-
return [
|
|
2397
|
-
`CREATE ${unique}INDEX IF NOT EXISTS ${quoteIdentifier(indexName)} ON ${quoteIdentifier(tableName)}(${columns}) WHERE ${index.where}`
|
|
2398
|
-
];
|
|
2399
|
-
}
|
|
2400
|
-
case "gin": {
|
|
2401
|
-
if (driver !== "pgsql") {
|
|
2402
|
-
throw new UnsupportedSchemaFeatureError("ginIndex()", driver);
|
|
2403
|
-
}
|
|
2404
|
-
return [
|
|
2405
|
-
`CREATE INDEX IF NOT EXISTS ${quoteIdentifier(indexName)} ON ${quoteIdentifier(tableName)} USING GIN(${columns})`
|
|
2406
|
-
];
|
|
2407
|
-
}
|
|
2408
|
-
case "fullText": {
|
|
2409
|
-
if (driver === "mysql") {
|
|
2410
|
-
return [
|
|
2411
|
-
`CREATE FULLTEXT INDEX ${quoteIdentifier(indexName)} ON ${quoteIdentifier(tableName)}(${columns})`
|
|
2412
|
-
];
|
|
2413
|
-
}
|
|
2414
|
-
if (driver === "pgsql") {
|
|
2415
|
-
throw new UnsupportedSchemaFeatureError("fullText(); use ginIndex() with a tsvector column on PostgreSQL", driver);
|
|
2416
|
-
}
|
|
2417
|
-
throw new UnsupportedSchemaFeatureError("fullText()", driver);
|
|
2418
|
-
}
|
|
2419
|
-
default:
|
|
2420
|
-
return [];
|
|
2421
|
-
}
|
|
2422
|
-
}
|
|
2423
|
-
function defaultIndexName(tableName, columns, kind) {
|
|
2424
|
-
return `idx_${tableName}_${columns.join("_")}_${kind}`;
|
|
2425
|
-
}
|
|
2426
|
-
function compileBlueprint(driver, blueprint) {
|
|
2427
|
-
switch (blueprint.action) {
|
|
2428
|
-
case "create":
|
|
2429
|
-
return compileCreateTable(driver, blueprint);
|
|
2430
|
-
case "alter":
|
|
2431
|
-
return compileAlterTable(driver, blueprint);
|
|
2432
|
-
case "drop":
|
|
2433
|
-
return compileDropTable(driver, blueprint.table);
|
|
2434
|
-
default:
|
|
2435
|
-
throw new Error(`Unsupported blueprint action: ${blueprint.action}`);
|
|
2436
|
-
}
|
|
2437
|
-
}
|
|
2438
|
-
// ../../src/core/database/schema/grammars/createGrammar.ts
|
|
2439
|
-
function createGrammar(driver) {
|
|
2440
|
-
return {
|
|
2441
|
-
driver,
|
|
2442
|
-
compile(blueprint) {
|
|
2443
|
-
return compileBlueprint(driver, blueprint);
|
|
2444
|
-
}
|
|
2445
|
-
};
|
|
2446
|
-
}
|
|
2447
|
-
|
|
2448
|
-
// ../../src/core/database/schema/grammars/mysqlGrammar.ts
|
|
2449
|
-
var MySqlGrammar = createGrammar("mysql");
|
|
2450
|
-
|
|
2451
|
-
// ../../src/core/database/schema/grammars/postgresGrammar.ts
|
|
2452
|
-
var PostgresGrammar = createGrammar("pgsql");
|
|
2453
|
-
|
|
2454
|
-
// ../../src/core/database/schema/grammars/sqliteGrammar.ts
|
|
2455
|
-
var SqliteGrammar = createGrammar("sqlite");
|
|
2456
|
-
|
|
2457
|
-
// ../../src/core/database/schema/grammars/index.ts
|
|
2458
|
-
function grammarForDriver(driver) {
|
|
2459
|
-
switch (driver) {
|
|
2460
|
-
case "pgsql":
|
|
2461
|
-
return PostgresGrammar;
|
|
2462
|
-
case "mysql":
|
|
2463
|
-
return MySqlGrammar;
|
|
2464
|
-
case "sqlite":
|
|
2465
|
-
return SqliteGrammar;
|
|
2466
|
-
default:
|
|
2467
|
-
throw new Error(`Unsupported database driver: ${driver}`);
|
|
2468
|
-
}
|
|
2469
|
-
}
|
|
2470
|
-
// ../../src/core/database/schema/schema.ts
|
|
2471
|
-
class SchemaBuilder {
|
|
2472
|
-
#driver;
|
|
2473
|
-
#statements = [];
|
|
2474
|
-
constructor(driver) {
|
|
2475
|
-
this.#driver = driver;
|
|
2476
|
-
}
|
|
2477
|
-
create(table, callback) {
|
|
2478
|
-
const blueprint = new Blueprint(table, "create");
|
|
2479
|
-
callback(blueprint);
|
|
2480
|
-
this.#statements.push(...grammarForDriver(this.#driver).compile(blueprint));
|
|
2481
|
-
return this;
|
|
2482
|
-
}
|
|
2483
|
-
table(table, callback) {
|
|
2484
|
-
const blueprint = new Blueprint(table, "alter");
|
|
2485
|
-
callback(blueprint);
|
|
2486
|
-
this.#statements.push(...grammarForDriver(this.#driver).compile(blueprint));
|
|
2487
|
-
return this;
|
|
2488
|
-
}
|
|
2489
|
-
drop(table) {
|
|
2490
|
-
const blueprint = new Blueprint(table, "drop");
|
|
2491
|
-
this.#statements.push(...grammarForDriver(this.#driver).compile(blueprint));
|
|
2492
|
-
return this;
|
|
2493
|
-
}
|
|
2494
|
-
toSql() {
|
|
2495
|
-
return [...this.#statements];
|
|
2496
|
-
}
|
|
2497
|
-
async execute(db2) {
|
|
2498
|
-
for (const statement of this.#statements) {
|
|
2499
|
-
await db2.unsafe(statement);
|
|
2500
|
-
}
|
|
2501
|
-
}
|
|
2502
|
-
}
|
|
2503
|
-
|
|
2504
|
-
class Schema {
|
|
2505
|
-
static builder(driver) {
|
|
2506
|
-
return new SchemaBuilder(driver ?? resolveDatabaseDriver());
|
|
2507
|
-
}
|
|
2508
|
-
static async run(db2, driver, callback) {
|
|
2509
|
-
const schema = Schema.builder(driver);
|
|
2510
|
-
await callback(schema);
|
|
2511
|
-
await schema.execute(db2);
|
|
2512
|
-
}
|
|
2513
|
-
}
|
|
2514
|
-
function createSchemaBuilder(db2, driver) {
|
|
2515
|
-
const builder = Schema.builder(driver);
|
|
2516
|
-
return Object.assign(builder, {
|
|
2517
|
-
async commit() {
|
|
2518
|
-
await builder.execute(db2);
|
|
2519
|
-
}
|
|
2520
|
-
});
|
|
2521
|
-
}
|
|
2522
|
-
// ../../src/core/database/table.ts
|
|
2523
|
-
function defineTable(definition) {
|
|
2524
|
-
return definition;
|
|
2525
|
-
}
|
|
2526
|
-
// ../../src/core/database/transaction.ts
|
|
2527
|
-
function supportsTransactions(connection) {
|
|
2528
|
-
return typeof connection.begin === "function";
|
|
2529
|
-
}
|
|
2530
|
-
async function runInTransaction(operation) {
|
|
2531
|
-
const pool = resolveRepositoryConnection();
|
|
2532
|
-
if (!supportsTransactions(pool)) {
|
|
2533
|
-
throw new Error("Active database connection does not support transactions. Bind a client with begin() via bindDatabaseConnection.");
|
|
2534
|
-
}
|
|
2535
|
-
return await pool.begin(async (transaction) => {
|
|
2536
|
-
return await operation(createDatabaseConnection2(transaction));
|
|
2537
|
-
});
|
|
2538
|
-
}
|
|
2539
|
-
// ../../src/modules/user/apiTokenTable.ts
|
|
2540
|
-
var apiTokenTable = defineTable({
|
|
2541
|
-
name: "api_token",
|
|
2542
|
-
primaryKey: "id",
|
|
2543
|
-
columns: [
|
|
2544
|
-
"id",
|
|
2545
|
-
"user_id",
|
|
2546
|
-
"name",
|
|
2547
|
-
"token_hash",
|
|
2548
|
-
"abilities",
|
|
2549
|
-
"last_used_at",
|
|
2550
|
-
"expires_at",
|
|
2551
|
-
"created_at"
|
|
2552
|
-
],
|
|
2553
|
-
defaultOrderBy: { column: "id", direction: "ASC" }
|
|
2554
|
-
});
|
|
2555
|
-
|
|
2556
|
-
// ../../src/core/auth/password.ts
|
|
2557
|
-
async function hashPassword(password) {
|
|
2558
|
-
return await Bun.password.hash(password, {
|
|
2559
|
-
algorithm: "bcrypt",
|
|
2560
|
-
cost: 10
|
|
2561
|
-
});
|
|
2562
|
-
}
|
|
2563
|
-
async function verifyPassword(password, passwordHash) {
|
|
2564
|
-
return await Bun.password.verify(password, passwordHash);
|
|
2565
|
-
}
|
|
2566
|
-
|
|
2567
|
-
// ../../src/core/crypto/fieldEncryption.ts
|
|
2568
|
-
import { createCipheriv, createDecipheriv, createHmac, randomBytes } from "crypto";
|
|
2569
|
-
var ENCRYPTION_PREFIX = "enc:v1:";
|
|
2570
|
-
var IV_LENGTH = 12;
|
|
2571
|
-
var TAG_LENGTH = 16;
|
|
2572
|
-
function resolveEncryptionKey() {
|
|
2573
|
-
const raw = process.env.KMS_ENCRYPTION_KEY?.trim();
|
|
2574
|
-
if (!raw) {
|
|
2575
|
-
return null;
|
|
2576
|
-
}
|
|
2577
|
-
if (/^[0-9a-f]{64}$/i.test(raw)) {
|
|
2578
|
-
return Buffer.from(raw, "hex");
|
|
2579
|
-
}
|
|
2580
|
-
const decoded = Buffer.from(raw, "base64");
|
|
2581
|
-
if (decoded.length === 32) {
|
|
2582
|
-
return decoded;
|
|
2583
|
-
}
|
|
2584
|
-
throw new Error("KMS_ENCRYPTION_KEY must be 32 bytes (hex or base64).");
|
|
2585
|
-
}
|
|
2586
|
-
function isFieldEncryptionEnabled() {
|
|
2587
|
-
const featureFlag = process.env.FEATURE_FIELD_ENCRYPTION;
|
|
2588
|
-
if (featureFlag === "false") {
|
|
2589
|
-
return false;
|
|
2590
|
-
}
|
|
2591
|
-
if (featureFlag === "true") {
|
|
2592
|
-
return true;
|
|
2593
|
-
}
|
|
2594
|
-
return (process.env.APP_ENV ?? "local") === "production";
|
|
2595
|
-
}
|
|
2596
|
-
function encryptField(plaintext, key) {
|
|
2597
|
-
const iv = randomBytes(IV_LENGTH);
|
|
2598
|
-
const cipher = createCipheriv("aes-256-gcm", key, iv);
|
|
2599
|
-
const encrypted = Buffer.concat([cipher.update(plaintext, "utf8"), cipher.final()]);
|
|
2600
|
-
const tag = cipher.getAuthTag();
|
|
2601
|
-
const payload = Buffer.concat([iv, encrypted, tag]).toString("base64");
|
|
2602
|
-
return `${ENCRYPTION_PREFIX}${payload}`;
|
|
2603
|
-
}
|
|
2604
|
-
function decryptField(value, key) {
|
|
2605
|
-
if (!value.startsWith(ENCRYPTION_PREFIX)) {
|
|
2606
|
-
return value;
|
|
2607
|
-
}
|
|
2608
|
-
const payload = Buffer.from(value.slice(ENCRYPTION_PREFIX.length), "base64");
|
|
2609
|
-
const iv = payload.subarray(0, IV_LENGTH);
|
|
2610
|
-
const tag = payload.subarray(payload.length - TAG_LENGTH);
|
|
2611
|
-
const ciphertext = payload.subarray(IV_LENGTH, payload.length - TAG_LENGTH);
|
|
2612
|
-
const decipher = createDecipheriv("aes-256-gcm", key, iv);
|
|
2613
|
-
decipher.setAuthTag(tag);
|
|
2614
|
-
return Buffer.concat([decipher.update(ciphertext), decipher.final()]).toString("utf8");
|
|
2615
|
-
}
|
|
2616
|
-
function hashLookupValue(normalizedValue, key) {
|
|
2617
|
-
return createHmac("sha256", key).update(normalizedValue).digest("hex");
|
|
2618
|
-
}
|
|
2619
|
-
function normalizeEmail(email) {
|
|
2620
|
-
return email.trim().toLowerCase();
|
|
2621
|
-
}
|
|
2622
|
-
function protectEmail(email) {
|
|
2623
|
-
const normalized = normalizeEmail(email);
|
|
2624
|
-
const key = resolveEncryptionKey();
|
|
2625
|
-
if (!key || !isFieldEncryptionEnabled()) {
|
|
2626
|
-
return { storedEmail: normalized, emailLookup: normalized };
|
|
2627
|
-
}
|
|
2628
|
-
return {
|
|
2629
|
-
storedEmail: encryptField(normalized, key),
|
|
2630
|
-
emailLookup: hashLookupValue(normalized, key)
|
|
2631
|
-
};
|
|
2632
|
-
}
|
|
2633
|
-
function revealEmail(storedEmail) {
|
|
2634
|
-
const key = resolveEncryptionKey();
|
|
2635
|
-
if (!key || !storedEmail.startsWith(ENCRYPTION_PREFIX)) {
|
|
2636
|
-
return storedEmail;
|
|
2637
|
-
}
|
|
2638
|
-
return decryptField(storedEmail, key);
|
|
2639
|
-
}
|
|
2640
|
-
function emailLookupForQuery(email) {
|
|
2641
|
-
const normalized = normalizeEmail(email);
|
|
2642
|
-
const key = resolveEncryptionKey();
|
|
2643
|
-
if (!key || !isFieldEncryptionEnabled()) {
|
|
2644
|
-
return normalized;
|
|
2645
|
-
}
|
|
2646
|
-
return hashLookupValue(normalized, key);
|
|
2647
|
-
}
|
|
2648
|
-
|
|
2649
|
-
// ../../src/core/crypto/mfaSecret.ts
|
|
2650
|
-
function protectMfaSecret(secret) {
|
|
2651
|
-
const key = resolveEncryptionKey();
|
|
2652
|
-
if (!isFieldEncryptionEnabled() || !key) {
|
|
2653
|
-
return secret;
|
|
2654
|
-
}
|
|
2655
|
-
return encryptField(secret, key);
|
|
2656
|
-
}
|
|
2657
|
-
function revealMfaSecret(stored) {
|
|
2658
|
-
if (!stored) {
|
|
2659
|
-
return null;
|
|
2660
|
-
}
|
|
2661
|
-
const key = resolveEncryptionKey();
|
|
2662
|
-
if (!isFieldEncryptionEnabled() || !key || !stored.startsWith("enc:v1:")) {
|
|
2663
|
-
return stored;
|
|
2664
|
-
}
|
|
2665
|
-
return decryptField(stored, key);
|
|
2666
|
-
}
|
|
2667
|
-
|
|
2668
|
-
// ../../src/core/auth/authContext.ts
|
|
2669
|
-
import { AsyncLocalStorage as AsyncLocalStorage2 } from "async_hooks";
|
|
2670
|
-
var authContext = new AsyncLocalStorage2;
|
|
2671
|
-
function runWithAuthUser(user, callback) {
|
|
2672
|
-
return authContext.run(user, callback);
|
|
2673
|
-
}
|
|
2674
|
-
function currentAuthUser() {
|
|
2675
|
-
return authContext.getStore() ?? null;
|
|
2676
|
-
}
|
|
2677
|
-
|
|
2678
|
-
// ../../src/core/http/requestMetaContext.ts
|
|
2679
|
-
import { AsyncLocalStorage as AsyncLocalStorage3 } from "async_hooks";
|
|
2680
|
-
var requestMetaContext = new AsyncLocalStorage3;
|
|
2681
|
-
function runWithRequestMeta(meta, callback) {
|
|
2682
|
-
return requestMetaContext.run(meta, callback);
|
|
2683
|
-
}
|
|
2684
|
-
function currentRequestMeta() {
|
|
2685
|
-
return requestMetaContext.getStore() ?? {
|
|
2686
|
-
ipAddress: null,
|
|
2687
|
-
userAgent: null
|
|
2688
|
-
};
|
|
2689
|
-
}
|
|
2690
|
-
|
|
2691
|
-
// ../../src/core/security/securityEvents.ts
|
|
2692
|
-
function logSecurityEvent(event, details = {}) {
|
|
2693
|
-
const meta = currentRequestMeta();
|
|
2694
|
-
const user = currentAuthUser();
|
|
2695
|
-
console.log(JSON.stringify({
|
|
2696
|
-
level: "security",
|
|
2697
|
-
event,
|
|
2698
|
-
timestamp: new Date().toISOString(),
|
|
2699
|
-
ip_address: meta.ipAddress ?? null,
|
|
2700
|
-
user_agent: meta.userAgent ?? null,
|
|
2701
|
-
user_id: user?.id ?? null,
|
|
2702
|
-
...details
|
|
2703
|
-
}));
|
|
2704
|
-
}
|
|
2705
|
-
|
|
2706
|
-
// ../../src/core/security/tokenExpiry.ts
|
|
2707
|
-
function resolveDefaultTokenExpiryDays() {
|
|
2708
|
-
const raw = process.env.API_TOKEN_DEFAULT_EXPIRY_DAYS?.trim();
|
|
2709
|
-
if (!raw) {
|
|
2710
|
-
return null;
|
|
2711
|
-
}
|
|
2712
|
-
const parsed = Number.parseInt(raw, 10);
|
|
2713
|
-
if (!Number.isInteger(parsed) || parsed <= 0) {
|
|
2714
|
-
return null;
|
|
2715
|
-
}
|
|
2716
|
-
return parsed;
|
|
2717
|
-
}
|
|
2718
|
-
|
|
2719
|
-
// ../../src/core/security/totp.ts
|
|
2720
|
-
import { createHmac as createHmac2 } from "crypto";
|
|
2721
|
-
function decodeBase32(input) {
|
|
2722
|
-
const alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
|
|
2723
|
-
const normalized = input.replace(/=+$/u, "").toUpperCase();
|
|
2724
|
-
let bits = "";
|
|
2725
|
-
for (const char of normalized) {
|
|
2726
|
-
const value = alphabet.indexOf(char);
|
|
2727
|
-
if (value === -1) {
|
|
2728
|
-
throw new Error("Invalid base32 character in MFA secret.");
|
|
2729
|
-
}
|
|
2730
|
-
bits += value.toString(2).padStart(5, "0");
|
|
2731
|
-
}
|
|
2732
|
-
const bytes = [];
|
|
2733
|
-
for (let index = 0;index + 8 <= bits.length; index += 8) {
|
|
2734
|
-
bytes.push(Number.parseInt(bits.slice(index, index + 8), 2));
|
|
2735
|
-
}
|
|
2736
|
-
return Buffer.from(bytes);
|
|
2737
|
-
}
|
|
2738
|
-
function generateTotp(secret, counter, digits = 6) {
|
|
2739
|
-
const key = decodeBase32(secret);
|
|
2740
|
-
const buffer = Buffer.alloc(8);
|
|
2741
|
-
buffer.writeBigUInt64BE(BigInt(counter));
|
|
2742
|
-
const digest = createHmac2("sha1", key).update(buffer).digest();
|
|
2743
|
-
const lastByte = digest[digest.length - 1] ?? 0;
|
|
2744
|
-
const offset = lastByte & 15;
|
|
2745
|
-
const b0 = digest[offset] ?? 0;
|
|
2746
|
-
const b1 = digest[offset + 1] ?? 0;
|
|
2747
|
-
const b2 = digest[offset + 2] ?? 0;
|
|
2748
|
-
const b3 = digest[offset + 3] ?? 0;
|
|
2749
|
-
const code = (b0 & 127) << 24 | (b1 & 255) << 16 | (b2 & 255) << 8 | b3 & 255;
|
|
2750
|
-
return String(code % 10 ** digits).padStart(digits, "0");
|
|
2751
|
-
}
|
|
2752
|
-
function verifyTotp(secret, token, window = 1) {
|
|
2753
|
-
const normalized = token.trim();
|
|
2754
|
-
if (!/^\d{6}$/u.test(normalized)) {
|
|
2755
|
-
return false;
|
|
2756
|
-
}
|
|
2757
|
-
const timestep = Math.floor(Date.now() / 30000);
|
|
2758
|
-
for (let offset = -window;offset <= window; offset += 1) {
|
|
2759
|
-
if (generateTotp(secret, timestep + offset) === normalized) {
|
|
2760
|
-
return true;
|
|
2761
|
-
}
|
|
2762
|
-
}
|
|
2763
|
-
return false;
|
|
2764
|
-
}
|
|
2765
|
-
|
|
2766
|
-
// ../../src/core/tenant/tenantContext.ts
|
|
2767
|
-
import { AsyncLocalStorage as AsyncLocalStorage4 } from "async_hooks";
|
|
2768
|
-
var tenantContext = new AsyncLocalStorage4;
|
|
2769
|
-
function runWithTenant(tenant, callback) {
|
|
2770
|
-
return tenantContext.run(tenant, callback);
|
|
2771
|
-
}
|
|
2772
|
-
function currentTenant() {
|
|
2773
|
-
return tenantContext.getStore() ?? null;
|
|
2774
|
-
}
|
|
2775
|
-
function currentTenantId() {
|
|
2776
|
-
return currentTenant()?.id ?? 1;
|
|
2777
|
-
}
|
|
2778
|
-
function rateLimitMultiplierForPlan(plan) {
|
|
2779
|
-
switch (plan) {
|
|
2780
|
-
case "enterprise":
|
|
2781
|
-
return 4;
|
|
2782
|
-
case "pro":
|
|
2783
|
-
return 2;
|
|
2784
|
-
default:
|
|
2785
|
-
return 1;
|
|
2786
|
-
}
|
|
2787
|
-
}
|
|
2788
|
-
|
|
2789
|
-
// ../../src/modules/user/authService.ts
|
|
2790
|
-
class AuthService {
|
|
2791
|
-
users;
|
|
2792
|
-
tokens;
|
|
2793
|
-
oauthIdentities;
|
|
2794
|
-
oauthProviders = new Map;
|
|
2795
|
-
constructor(users, tokens, oauthIdentities) {
|
|
2796
|
-
this.users = users;
|
|
2797
|
-
this.tokens = tokens;
|
|
2798
|
-
this.oauthIdentities = oauthIdentities;
|
|
2799
|
-
}
|
|
2800
|
-
registerOAuthProvider(provider) {
|
|
2801
|
-
this.oauthProviders.set(provider.name, provider);
|
|
2802
|
-
}
|
|
2803
|
-
getOAuthProvider(name) {
|
|
2804
|
-
return this.oauthProviders.get(name);
|
|
2805
|
-
}
|
|
2806
|
-
async loginWithPassword(email, password, options = {}) {
|
|
2807
|
-
const user = await this.users.findByEmail(email);
|
|
2808
|
-
if (!user?.password_hash) {
|
|
2809
|
-
logSecurityEvent("auth_login_failed", { reason: "unknown_user", email });
|
|
2810
|
-
throw new UnauthorizedError("Invalid credentials.");
|
|
2811
|
-
}
|
|
2812
|
-
const valid = await verifyPassword(password, user.password_hash);
|
|
2813
|
-
if (!valid) {
|
|
2814
|
-
logSecurityEvent("auth_login_failed", { reason: "invalid_password", user_id: user.id });
|
|
2815
|
-
throw new UnauthorizedError("Invalid credentials.");
|
|
2816
|
-
}
|
|
2817
|
-
if (isFeatureEnabled("emailVerification") && !user.email_verified_at) {
|
|
2818
|
-
logSecurityEvent("auth_login_blocked", { reason: "email_unverified", user_id: user.id });
|
|
2819
|
-
throw new UnauthorizedError("Email address is not verified.");
|
|
2820
|
-
}
|
|
2821
|
-
if (isFeatureEnabled("mfa") && user.mfa_enabled) {
|
|
2822
|
-
const mfaSecret = revealMfaSecret(user.mfa_secret);
|
|
2823
|
-
if (!mfaSecret || !options.mfaCode || !verifyTotp(mfaSecret, options.mfaCode)) {
|
|
2824
|
-
logSecurityEvent("auth_login_failed", { reason: "invalid_mfa", user_id: user.id });
|
|
2825
|
-
throw new UnauthorizedError("Invalid MFA code.");
|
|
2826
|
-
}
|
|
2827
|
-
}
|
|
2828
|
-
logSecurityEvent("auth_login_success", { user_id: user.id, method: "password" });
|
|
2829
|
-
return await this.tokens.createToken(user.id, {
|
|
2830
|
-
name: "password-login",
|
|
2831
|
-
abilities: resolveAbilitiesForRole(user.role),
|
|
2832
|
-
expiresInDays: resolveDefaultTokenExpiryDays() ?? undefined
|
|
2833
|
-
});
|
|
2834
|
-
}
|
|
2835
|
-
async loginWithOAuth(providerName, code) {
|
|
2836
|
-
const provider = this.oauthProviders.get(providerName);
|
|
2837
|
-
if (!provider) {
|
|
2838
|
-
throw new UnauthorizedError("Unsupported OAuth provider.");
|
|
2839
|
-
}
|
|
2840
|
-
const profile = await provider.exchangeCode(code);
|
|
2841
|
-
const user = await this.findOrCreateOAuthUser(providerName, profile);
|
|
2842
|
-
logSecurityEvent("auth_login_success", { user_id: user.id, method: `oauth:${providerName}` });
|
|
2843
|
-
return await this.tokens.createToken(user.id, {
|
|
2844
|
-
name: `${providerName}-oauth`,
|
|
2845
|
-
abilities: resolveAbilitiesForRole(user.role),
|
|
2846
|
-
expiresInDays: resolveDefaultTokenExpiryDays() ?? undefined
|
|
2847
|
-
});
|
|
2848
|
-
}
|
|
2849
|
-
buildOAuthAuthorizationUrl(providerName, state) {
|
|
2850
|
-
const provider = this.oauthProviders.get(providerName);
|
|
2851
|
-
if (!provider) {
|
|
2852
|
-
throw new UnauthorizedError("Unsupported OAuth provider.");
|
|
2853
|
-
}
|
|
2854
|
-
return provider.getAuthorizationUrl(state);
|
|
2855
|
-
}
|
|
2856
|
-
async findOrCreateOAuthUser(providerName, profile) {
|
|
2857
|
-
const existingIdentity = await this.oauthIdentities.findByProviderUser(providerName, profile.providerUserId);
|
|
2858
|
-
if (existingIdentity) {
|
|
2859
|
-
return await this.users.findByIdOrThrow(existingIdentity.user_id);
|
|
2860
|
-
}
|
|
2861
|
-
const existingUser = await this.users.findByEmail(profile.email);
|
|
2862
|
-
const user = existingUser ?? await this.users.create({
|
|
2863
|
-
name: profile.name,
|
|
2864
|
-
email: profile.email,
|
|
2865
|
-
role: "member",
|
|
2866
|
-
tenant_id: currentTenantId(),
|
|
2867
|
-
email_verified_at: new Date,
|
|
2868
|
-
created_at: new Date,
|
|
2869
|
-
updated_at: new Date
|
|
2870
|
-
});
|
|
2871
|
-
await this.oauthIdentities.create({
|
|
2872
|
-
user_id: user.id,
|
|
2873
|
-
provider: providerName,
|
|
2874
|
-
provider_user_id: profile.providerUserId,
|
|
2875
|
-
email: profile.email,
|
|
2876
|
-
created_at: new Date
|
|
2877
|
-
});
|
|
2878
|
-
return user;
|
|
2879
|
-
}
|
|
2880
|
-
}
|
|
2881
|
-
|
|
2882
|
-
// ../../src/modules/user/notificationTable.ts
|
|
2883
|
-
var notificationTable = defineTable({
|
|
2884
|
-
name: "notification",
|
|
2885
|
-
primaryKey: "id",
|
|
2886
|
-
columns: ["id", "user_id", "tenant_id", "type", "title", "body", "data", "read_at", "created_at"],
|
|
2887
|
-
defaultOrderBy: { column: "created_at", direction: "DESC" }
|
|
2888
|
-
});
|
|
2889
|
-
|
|
2890
|
-
// ../../src/modules/user/oauthIdentityRepository.ts
|
|
2891
|
-
var oauthIdentityTable = defineTable({
|
|
2892
|
-
name: "oauth_identity",
|
|
2893
|
-
primaryKey: "id",
|
|
2894
|
-
columns: ["id", "user_id", "provider", "provider_user_id", "email", "created_at"]
|
|
2895
|
-
});
|
|
2896
|
-
|
|
2897
|
-
// ../../src/modules/user/table.ts
|
|
2898
|
-
var userTable = defineTable({
|
|
2899
|
-
name: "users",
|
|
2900
|
-
primaryKey: "id",
|
|
2901
|
-
columns: [
|
|
2902
|
-
"id",
|
|
2903
|
-
"name",
|
|
2904
|
-
"email",
|
|
2905
|
-
"email_lookup",
|
|
2906
|
-
"role",
|
|
2907
|
-
"tenant_id",
|
|
2908
|
-
"password_hash",
|
|
2909
|
-
"email_verified_at",
|
|
2910
|
-
"mfa_secret",
|
|
2911
|
-
"mfa_enabled",
|
|
2912
|
-
"created_at",
|
|
2913
|
-
"updated_at"
|
|
2914
|
-
],
|
|
2915
|
-
defaultOrderBy: { column: "id", direction: "ASC" }
|
|
2916
|
-
});
|
|
2917
|
-
|
|
2918
|
-
// ../../src/core/auth/tokenHash.ts
|
|
2919
|
-
import { createHash, createHmac as createHmac3 } from "crypto";
|
|
2920
|
-
function resolveTokenPepper() {
|
|
2921
|
-
return process.env.TOKEN_HASH_PEPPER?.trim() ?? "workhub-dev-token-pepper";
|
|
2922
|
-
}
|
|
2923
|
-
function hashApiToken(token) {
|
|
2924
|
-
const pepper = resolveTokenPepper();
|
|
2925
|
-
if (pepper && pepper !== "workhub-dev-token-pepper") {
|
|
2926
|
-
return createHmac3("sha256", pepper).update(token).digest("hex");
|
|
2927
|
-
}
|
|
2928
|
-
return createHash("sha256").update(token).digest("hex");
|
|
2929
|
-
}
|
|
2930
|
-
|
|
2931
|
-
// ../../src/modules/user/provider.ts
|
|
2932
|
-
var tokenServiceToken = CORE_TOKEN_SERVICE_TOKEN;
|
|
2933
|
-
|
|
2934
|
-
// ../../src/core/auth/guard.ts
|
|
2935
|
-
function devHeaderAbilities(role) {
|
|
2936
|
-
if (role === "admin") {
|
|
2937
|
-
return [...ADMIN_ABILITIES];
|
|
2938
|
-
}
|
|
2939
|
-
return [...MEMBER_ABILITIES];
|
|
2940
|
-
}
|
|
2941
|
-
|
|
2942
|
-
class GuestGuard {
|
|
2943
|
-
resolve(request) {
|
|
2944
|
-
const userId = request.headers.get("x-authenticated-user-id");
|
|
2945
|
-
if (!userId) {
|
|
2946
|
-
return null;
|
|
2947
|
-
}
|
|
2948
|
-
const role = request.headers.get("x-authenticated-user-role");
|
|
2949
|
-
return {
|
|
2950
|
-
id: userId,
|
|
2951
|
-
abilities: devHeaderAbilities(role),
|
|
2952
|
-
...role ? { role } : {}
|
|
2953
|
-
};
|
|
2954
|
-
}
|
|
2955
|
-
}
|
|
2956
|
-
|
|
2957
|
-
class ApiTokenGuard {
|
|
2958
|
-
options;
|
|
2959
|
-
constructor(options) {
|
|
2960
|
-
this.options = options;
|
|
2961
|
-
}
|
|
2962
|
-
resolve(request) {
|
|
2963
|
-
const authorization = request.headers.get("authorization");
|
|
2964
|
-
if (!authorization?.startsWith("Bearer ")) {
|
|
2965
|
-
return null;
|
|
2966
|
-
}
|
|
2967
|
-
const token = authorization.slice("Bearer ".length).trim();
|
|
2968
|
-
if (token !== this.options.token) {
|
|
2969
|
-
return null;
|
|
2970
|
-
}
|
|
2971
|
-
return this.options.user;
|
|
2972
|
-
}
|
|
2973
|
-
}
|
|
2974
|
-
|
|
2975
|
-
class DatabaseTokenGuard {
|
|
2976
|
-
container;
|
|
2977
|
-
constructor(container) {
|
|
2978
|
-
this.container = container;
|
|
2979
|
-
}
|
|
2980
|
-
async resolve(request) {
|
|
2981
|
-
const authorization = request.headers.get("authorization");
|
|
2982
|
-
if (!authorization?.startsWith("Bearer ")) {
|
|
2983
|
-
return null;
|
|
2984
|
-
}
|
|
2985
|
-
const token = authorization.slice("Bearer ".length).trim();
|
|
2986
|
-
if (!token) {
|
|
2987
|
-
return null;
|
|
2988
|
-
}
|
|
2989
|
-
if (!this.container.has(tokenServiceToken)) {
|
|
2990
|
-
return null;
|
|
2991
|
-
}
|
|
2992
|
-
const tokenService = this.container.resolve(tokenServiceToken);
|
|
2993
|
-
return await tokenService.resolveUserFromToken(token);
|
|
2994
|
-
}
|
|
2995
|
-
}
|
|
2996
|
-
|
|
2997
|
-
class CompositeGuard {
|
|
2998
|
-
guards;
|
|
2999
|
-
constructor(guards) {
|
|
3000
|
-
this.guards = guards;
|
|
3001
|
-
}
|
|
3002
|
-
async resolve(request) {
|
|
3003
|
-
for (const guard of this.guards) {
|
|
3004
|
-
const user = await Promise.resolve(guard.resolve(request));
|
|
3005
|
-
if (user) {
|
|
3006
|
-
return user;
|
|
3007
|
-
}
|
|
3008
|
-
}
|
|
3009
|
-
return null;
|
|
3010
|
-
}
|
|
3011
|
-
}
|
|
3012
|
-
|
|
3013
|
-
class AuthManager {
|
|
3014
|
-
guard;
|
|
3015
|
-
constructor(guard) {
|
|
3016
|
-
this.guard = guard;
|
|
3017
|
-
}
|
|
3018
|
-
async resolve(request) {
|
|
3019
|
-
if (request) {
|
|
3020
|
-
return await Promise.resolve(this.guard.resolve(request));
|
|
3021
|
-
}
|
|
3022
|
-
return currentAuthUser();
|
|
3023
|
-
}
|
|
3024
|
-
user(request) {
|
|
3025
|
-
return this.resolve(request);
|
|
3026
|
-
}
|
|
3027
|
-
async check(request) {
|
|
3028
|
-
return await this.user(request) !== null;
|
|
3029
|
-
}
|
|
3030
|
-
async requireUser(request) {
|
|
3031
|
-
const user = await this.user(request);
|
|
3032
|
-
if (!user) {
|
|
3033
|
-
throw new UnauthorizedError;
|
|
3034
|
-
}
|
|
3035
|
-
return user;
|
|
3036
|
-
}
|
|
3037
|
-
}
|
|
3038
|
-
export {
|
|
3039
|
-
GuestGuard,
|
|
3040
|
-
DatabaseTokenGuard,
|
|
3041
|
-
CompositeGuard,
|
|
3042
|
-
AuthManager,
|
|
3043
|
-
ApiTokenGuard
|
|
3044
|
-
};
|
|
1
|
+
export * from "../../index.js";
|