@getstrata/core 0.5.48 → 0.5.50

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