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