@getstrata/core 0.5.41 → 0.5.43

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 (46) hide show
  1. package/dist/core/database/baseRepository.d.ts +1 -0
  2. package/dist/core/queue/failedJobRepository.d.ts +1 -0
  3. package/dist/entries/admin/formatValue.js +32 -0
  4. package/dist/entries/admin/registry.js +32 -0
  5. package/dist/entries/audit/exportAuditLogs.js +18 -0
  6. package/dist/entries/audit/siemFormatter.js +37 -0
  7. package/dist/entries/auth/scimAuthMiddleware.js +241 -0
  8. package/dist/entries/auth/sessionGuard.js +501 -0
  9. package/dist/entries/database/baseRepository.js +1388 -0
  10. package/dist/entries/database/bindConnection.js +22 -0
  11. package/dist/entries/database/boundConnection.js +19 -0
  12. package/dist/entries/database/connection.js +12 -0
  13. package/dist/entries/database/errors.js +128 -0
  14. package/dist/entries/database/model.js +948 -0
  15. package/dist/entries/database/query.js +436 -0
  16. package/dist/entries/database/relationships.js +162 -0
  17. package/dist/entries/database/schema.js +1054 -0
  18. package/dist/entries/database/table.js +8 -0
  19. package/dist/entries/database/transaction.js +129 -0
  20. package/dist/entries/http/authMiddleware.js +47 -0
  21. package/dist/entries/http/authorizeMiddleware.js +104 -0
  22. package/dist/entries/http/metricsMiddleware.js +91 -0
  23. package/dist/entries/http/parseMultipartUpload.js +144 -0
  24. package/dist/entries/http/securedRouteModelBinding.js +6 -0
  25. package/dist/entries/http/webErrorResponse.js +501 -0
  26. package/dist/entries/http/webFormRequest.js +6 -0
  27. package/dist/entries/jobs/dispatchWebhookJob.js +18 -0
  28. package/dist/entries/mail/mailer.js +208 -0
  29. package/dist/entries/mail/markdownMail.js +63 -0
  30. package/dist/entries/mail/markdownMailable.js +78 -0
  31. package/dist/entries/notifications.js +152 -0
  32. package/dist/entries/openapi/generator.js +178 -0
  33. package/dist/entries/openapi/validate.js +28 -0
  34. package/dist/entries/queue/createAppQueue.js +507 -0
  35. package/dist/entries/queue/failedJobRepository.js +2364 -0
  36. package/dist/entries/queue/publicQueue.js +507 -0
  37. package/dist/entries/queue/queueMetrics.js +507 -0
  38. package/dist/entries/queue/redisQueue.js +232 -0
  39. package/dist/entries/runtime/asyncContextStore.js +17 -0
  40. package/dist/entries/security/safeFetch.js +211 -0
  41. package/dist/entries/security/scimTenantTokens.js +51 -0
  42. package/dist/entries/security/timingSafeCompare.js +14 -0
  43. package/dist/entries/tenant/databaseTenantContext.js +116 -0
  44. package/dist/entries/tenant/tenantDatabaseScope.js +113 -0
  45. package/dist/entries/view.js +501 -0
  46. package/package.json +167 -2
@@ -0,0 +1,232 @@
1
+ // @bun
2
+ // ../../src/core/queue/redisQueue.ts
3
+ var {RedisClient } = globalThis.Bun;
4
+
5
+ // ../../src/core/queue/jobRegistry.ts
6
+ class JobRegistry {
7
+ factories = new Map;
8
+ instances = new WeakMap;
9
+ register(name, factory) {
10
+ this.factories.set(name, factory);
11
+ }
12
+ resolveName(job) {
13
+ return this.instances.get(job);
14
+ }
15
+ track(name, job) {
16
+ this.instances.set(job, name);
17
+ return job;
18
+ }
19
+ create(name) {
20
+ const factory = this.factories.get(name);
21
+ if (!factory) {
22
+ return;
23
+ }
24
+ return factory();
25
+ }
26
+ names() {
27
+ return [...this.factories.keys()];
28
+ }
29
+ }
30
+ var JOB_REGISTRY_KEY = Symbol.for("@getstrata/jobRegistry");
31
+ function readSharedJobRegistry() {
32
+ const globalRegistry = globalThis[JOB_REGISTRY_KEY];
33
+ if (globalRegistry) {
34
+ return globalRegistry;
35
+ }
36
+ const registry = new JobRegistry;
37
+ globalThis[JOB_REGISTRY_KEY] = registry;
38
+ return registry;
39
+ }
40
+ var jobRegistry = readSharedJobRegistry();
41
+
42
+ // ../../src/core/contracts/serviceTokens.ts
43
+ var CORE_CONFIG_TOKEN = "core.config";
44
+ var CORE_CACHE_TOKEN = "core.cache";
45
+ var CORE_QUEUE_TOKEN = "core.queue";
46
+ var CORE_EVENT_BUS_TOKEN = "core.eventBus";
47
+ var CORE_POLICY_GATE_TOKEN = "core.policyGate";
48
+ var CORE_AUTH_TOKEN = "core.auth";
49
+ var CORE_TOKEN_SERVICE_TOKEN = "core.tokenService";
50
+ // ../../src/bootstrap/config.ts
51
+ var DEFAULT_QUEUE_DRIVER = "sync";
52
+
53
+ // ../../src/config/queue.ts
54
+ var queueConfig = {
55
+ driver: process.env.QUEUE_DRIVER === "redis" || process.env.QUEUE_DRIVER === "async" || process.env.QUEUE_DRIVER === "sync" ? process.env.QUEUE_DRIVER : DEFAULT_QUEUE_DRIVER,
56
+ maxAttempts: Number(process.env.QUEUE_MAX_ATTEMPTS ?? "3"),
57
+ backoffMs: Number(process.env.QUEUE_BACKOFF_MS ?? "1000")
58
+ };
59
+
60
+ // ../../src/core/queue/jobRunner.ts
61
+ async function runQueueJob(envelope, failedJobs) {
62
+ const job = jobRegistry.create(envelope.name);
63
+ if (!job) {
64
+ throw new Error(`Unknown job "${envelope.name}".`);
65
+ }
66
+ const attempts = envelope.attempts ?? 0;
67
+ try {
68
+ await job.handle(envelope.payload);
69
+ } catch (error) {
70
+ const nextAttempt = attempts + 1;
71
+ const maxAttempts = job.maxAttempts ?? queueConfig.maxAttempts;
72
+ if (nextAttempt < maxAttempts) {
73
+ const backoffMs = job.backoffMs ?? queueConfig.backoffMs;
74
+ await new Promise((resolve) => setTimeout(resolve, backoffMs * nextAttempt));
75
+ await runQueueJob({
76
+ ...envelope,
77
+ attempts: nextAttempt
78
+ }, failedJobs);
79
+ return;
80
+ }
81
+ await failedJobs.recordFailure({
82
+ jobName: envelope.name,
83
+ payload: envelope.payload,
84
+ exception: error instanceof Error ? error.stack ?? error.message : String(error)
85
+ });
86
+ throw error;
87
+ }
88
+ }
89
+
90
+ // ../../src/core/queue/redisQueue.ts
91
+ var QUEUE_LIST_KEY = "workhub:queue:default";
92
+ var QUEUE_HIGH_KEY = "workhub:queue:high";
93
+ var QUEUE_LOW_KEY = "workhub:queue:low";
94
+ var QUEUE_KEYS = [QUEUE_HIGH_KEY, QUEUE_LIST_KEY, QUEUE_LOW_KEY];
95
+ function queueKeyForPriority(priority = "default") {
96
+ switch (priority) {
97
+ case "high":
98
+ return QUEUE_HIGH_KEY;
99
+ case "low":
100
+ return QUEUE_LOW_KEY;
101
+ default:
102
+ return QUEUE_LIST_KEY;
103
+ }
104
+ }
105
+ function parseQueueJobEnvelope(rawPayload) {
106
+ let parsed;
107
+ try {
108
+ parsed = JSON.parse(rawPayload);
109
+ } catch {
110
+ console.error("[QueueWorker] Ignoring malformed queue payload");
111
+ return null;
112
+ }
113
+ if (!parsed || typeof parsed !== "object") {
114
+ console.error("[QueueWorker] Ignoring non-object queue payload");
115
+ return null;
116
+ }
117
+ const envelope = parsed;
118
+ if (typeof envelope.name !== "string" || envelope.name.length === 0) {
119
+ console.error("[QueueWorker] Ignoring queue payload without job name");
120
+ return null;
121
+ }
122
+ if (!jobRegistry.create(envelope.name)) {
123
+ console.error(`[QueueWorker] Ignoring unknown job name: ${envelope.name}`);
124
+ return null;
125
+ }
126
+ if (envelope.payload !== undefined && (typeof envelope.payload !== "object" || envelope.payload === null)) {
127
+ console.error("[QueueWorker] Ignoring queue payload with invalid payload object");
128
+ return null;
129
+ }
130
+ return {
131
+ name: envelope.name,
132
+ payload: envelope.payload ?? {},
133
+ attempts: typeof envelope.attempts === "number" ? envelope.attempts : 0
134
+ };
135
+ }
136
+
137
+ class RedisQueue {
138
+ client;
139
+ constructor(redisUrl) {
140
+ this.client = new RedisClient(redisUrl);
141
+ }
142
+ async dispatch(job, payload) {
143
+ const name = jobRegistry.resolveName(job);
144
+ if (!name) {
145
+ throw new Error("Job is not registered with the queue worker registry.");
146
+ }
147
+ const envelope = {
148
+ name,
149
+ payload,
150
+ attempts: 0
151
+ };
152
+ const queueKey = queueKeyForPriority(job.priority);
153
+ await this.client.lpush(queueKey, JSON.stringify(envelope));
154
+ }
155
+ }
156
+
157
+ class QueueWorker {
158
+ failedJobs;
159
+ timeoutSeconds;
160
+ running = false;
161
+ stopping = false;
162
+ client;
163
+ constructor(redisUrl, failedJobs, timeoutSeconds = 5) {
164
+ this.failedJobs = failedJobs;
165
+ this.timeoutSeconds = timeoutSeconds;
166
+ this.client = new RedisClient(redisUrl);
167
+ }
168
+ requestStop() {
169
+ this.stopping = true;
170
+ }
171
+ isRunning() {
172
+ return this.running;
173
+ }
174
+ async processNext() {
175
+ let result = null;
176
+ for (const queueKey of QUEUE_KEYS) {
177
+ result = await this.client.brpop(queueKey, 1);
178
+ if (result) {
179
+ break;
180
+ }
181
+ }
182
+ if (!result) {
183
+ result = await this.client.brpop(QUEUE_LIST_KEY, this.timeoutSeconds);
184
+ }
185
+ if (!result) {
186
+ return false;
187
+ }
188
+ const [, rawPayload] = result;
189
+ const envelope = parseQueueJobEnvelope(rawPayload);
190
+ if (!envelope) {
191
+ return true;
192
+ }
193
+ try {
194
+ await runQueueJob(envelope, this.failedJobs);
195
+ } catch (error) {
196
+ console.error("[QueueWorker] Job failed:", error);
197
+ }
198
+ return true;
199
+ }
200
+ async run() {
201
+ this.running = true;
202
+ while (!this.stopping) {
203
+ await this.processNext();
204
+ }
205
+ this.running = false;
206
+ }
207
+ close() {
208
+ this.client.close();
209
+ }
210
+ }
211
+ async function countPendingQueueJobs(redisUrl) {
212
+ const client = new RedisClient(redisUrl);
213
+ try {
214
+ let total = 0;
215
+ for (const queueKey of QUEUE_KEYS) {
216
+ total += await client.llen(queueKey);
217
+ }
218
+ return total;
219
+ } finally {
220
+ client.close();
221
+ }
222
+ }
223
+ export {
224
+ queueKeyForPriority,
225
+ parseQueueJobEnvelope,
226
+ countPendingQueueJobs,
227
+ RedisQueue,
228
+ QueueWorker,
229
+ QUEUE_LOW_KEY,
230
+ QUEUE_LIST_KEY,
231
+ QUEUE_HIGH_KEY
232
+ };
@@ -0,0 +1,17 @@
1
+ // @bun
2
+ // ../../src/core/runtime/asyncContextStore.ts
3
+ import { AsyncLocalStorage } from "async_hooks";
4
+ function createAsyncContextStore(key) {
5
+ const symbol = Symbol.for(key);
6
+ const globalRecord = globalThis;
7
+ const existing = globalRecord[symbol];
8
+ if (existing) {
9
+ return existing;
10
+ }
11
+ const store = new AsyncLocalStorage;
12
+ globalRecord[symbol] = store;
13
+ return store;
14
+ }
15
+ export {
16
+ createAsyncContextStore
17
+ };
@@ -0,0 +1,211 @@
1
+ // @bun
2
+ // ../../src/config/app.ts
3
+ var appConfig = {
4
+ name: "WorkHub",
5
+ env: process.env.APP_ENV ?? "local",
6
+ debug: (process.env.APP_DEBUG ?? "true") !== "false",
7
+ url: process.env.APP_URL ?? "http://localhost:3000",
8
+ apiPrefix: process.env.API_PREFIX ?? "/api/v1"
9
+ };
10
+
11
+ // ../../src/core/security/safeUrl.ts
12
+ import { lookup as dnsLookupImpl } from "dns/promises";
13
+
14
+ // ../../src/core/errors/http.ts
15
+ class HttpError extends Error {
16
+ status;
17
+ details;
18
+ constructor(status, message, details) {
19
+ super(message);
20
+ this.name = new.target.name;
21
+ this.status = status;
22
+ this.details = details;
23
+ }
24
+ }
25
+
26
+ class BadRequestError extends HttpError {
27
+ constructor(message = "Bad Request", details) {
28
+ super(400, message, details);
29
+ }
30
+ }
31
+
32
+ class NotFoundError extends HttpError {
33
+ constructor(message = "Not Found", details) {
34
+ super(404, message, details);
35
+ }
36
+ }
37
+
38
+ class ConflictError extends HttpError {
39
+ constructor(message = "Conflict", details) {
40
+ super(409, message, details);
41
+ }
42
+ }
43
+
44
+ class UnprocessableEntityError extends HttpError {
45
+ constructor(message = "Unprocessable Entity", details) {
46
+ super(422, message, details);
47
+ }
48
+ }
49
+
50
+ class ValidationError extends HttpError {
51
+ constructor(message = "Validation failed", details) {
52
+ super(422, message, details);
53
+ }
54
+ }
55
+
56
+ class ForbiddenError extends HttpError {
57
+ constructor(message = "Forbidden", details) {
58
+ super(403, message, details);
59
+ }
60
+ }
61
+
62
+ class UnauthorizedError extends HttpError {
63
+ constructor(message = "Unauthorized", details) {
64
+ super(401, message, details);
65
+ }
66
+ }
67
+
68
+ class PayloadTooLargeError extends HttpError {
69
+ constructor(message = "Payload Too Large", details) {
70
+ super(413, message, details);
71
+ }
72
+ }
73
+
74
+ class PreconditionFailedError extends HttpError {
75
+ constructor(message = "Precondition Failed", details) {
76
+ super(412, message, details);
77
+ }
78
+ }
79
+
80
+ // ../../src/core/security/safeUrl.ts
81
+ var dnsLookup = dnsLookupImpl;
82
+ var BLOCKED_HOSTNAMES = new Set([
83
+ "localhost",
84
+ "127.0.0.1",
85
+ "0.0.0.0",
86
+ "::1",
87
+ "metadata.google.internal"
88
+ ]);
89
+ function isPrivateIpv4(hostname) {
90
+ const match = /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/.exec(hostname);
91
+ if (!match) {
92
+ return false;
93
+ }
94
+ const octets = match.slice(1, 5).map((part) => Number.parseInt(part, 10));
95
+ if (octets.some((octet) => octet < 0 || octet > 255)) {
96
+ return true;
97
+ }
98
+ const [a = 0, b = 0] = octets;
99
+ if (a === 10) {
100
+ return true;
101
+ }
102
+ if (a === 127) {
103
+ return true;
104
+ }
105
+ if (a === 0) {
106
+ return true;
107
+ }
108
+ if (a === 169 && b === 254) {
109
+ return true;
110
+ }
111
+ if (a === 172 && b >= 16 && b <= 31) {
112
+ return true;
113
+ }
114
+ if (a === 192 && b === 168) {
115
+ return true;
116
+ }
117
+ return false;
118
+ }
119
+ function isBlockedHostname(hostname) {
120
+ const normalized = hostname.trim().toLowerCase();
121
+ if (normalized.length === 0) {
122
+ return true;
123
+ }
124
+ if (BLOCKED_HOSTNAMES.has(normalized)) {
125
+ return true;
126
+ }
127
+ if (normalized.endsWith(".local") || normalized.endsWith(".internal")) {
128
+ return true;
129
+ }
130
+ if (normalized.includes(":")) {
131
+ return true;
132
+ }
133
+ return isPrivateIpv4(normalized);
134
+ }
135
+ function assertSafeOutboundUrl(rawUrl, options = {}) {
136
+ let parsed;
137
+ try {
138
+ parsed = new URL(rawUrl);
139
+ } catch {
140
+ throw new BadRequestError("Webhook URL is invalid.");
141
+ }
142
+ if (parsed.protocol !== "https:" && !(options.allowHttp && parsed.protocol === "http:")) {
143
+ throw new BadRequestError("Webhook URL must use HTTPS.");
144
+ }
145
+ if (parsed.username || parsed.password) {
146
+ throw new BadRequestError("Webhook URL must not include credentials.");
147
+ }
148
+ if (isBlockedHostname(parsed.hostname)) {
149
+ throw new BadRequestError("Webhook URL targets a blocked host.");
150
+ }
151
+ return parsed;
152
+ }
153
+ function isBlockedIpAddress(address) {
154
+ return isBlockedHostname(address.trim().toLowerCase());
155
+ }
156
+ async function assertSafeOutboundUrlResolved(rawUrl, options = {}) {
157
+ const parsed = assertSafeOutboundUrl(rawUrl, options);
158
+ if (options.resolveDns === false) {
159
+ return parsed;
160
+ }
161
+ const hostname = parsed.hostname.trim().toLowerCase();
162
+ const results = await dnsLookup(hostname, { all: true, verbatim: true });
163
+ if (results.some((result) => isBlockedIpAddress(result.address))) {
164
+ throw new BadRequestError("Webhook URL targets a blocked host.");
165
+ }
166
+ return parsed;
167
+ }
168
+ function setDnsLookupForTests(lookupFn) {
169
+ dnsLookup = lookupFn;
170
+ }
171
+ function resetDnsLookupForTests() {
172
+ dnsLookup = dnsLookupImpl;
173
+ }
174
+
175
+ // ../../src/core/security/safeFetch.ts
176
+ var DEFAULT_FETCH_TIMEOUT_MS = 1e4;
177
+ async function safeFetch(input, init = {}, options = {}) {
178
+ const timeoutMs = options.timeoutMs ?? DEFAULT_FETCH_TIMEOUT_MS;
179
+ const maxRedirects = options.maxRedirects ?? 0;
180
+ const resolveDns = options.resolveDns ?? appConfig.env === "production";
181
+ const urlOptions = { allowHttp: options.allowHttp, resolveDns };
182
+ const controller = new AbortController;
183
+ const timeout = setTimeout(() => controller.abort(), timeoutMs);
184
+ try {
185
+ let currentUrl = (await assertSafeOutboundUrlResolved(input, urlOptions)).toString();
186
+ let redirectCount = 0;
187
+ while (true) {
188
+ const response = await fetch(currentUrl, {
189
+ ...init,
190
+ signal: controller.signal,
191
+ redirect: "manual"
192
+ });
193
+ if (response.status >= 300 && response.status < 400) {
194
+ const location = response.headers.get("location");
195
+ if (!location || redirectCount >= maxRedirects) {
196
+ return response;
197
+ }
198
+ currentUrl = (await assertSafeOutboundUrlResolved(new URL(location, currentUrl).toString(), urlOptions)).toString();
199
+ redirectCount += 1;
200
+ continue;
201
+ }
202
+ return response;
203
+ }
204
+ } finally {
205
+ clearTimeout(timeout);
206
+ }
207
+ }
208
+ export {
209
+ safeFetch,
210
+ DEFAULT_FETCH_TIMEOUT_MS
211
+ };
@@ -0,0 +1,51 @@
1
+ // @bun
2
+ // ../../src/domain/scim.ts
3
+ var TEST_SCIM_BEARER_TOKEN = "workhub-scim-test-token";
4
+
5
+ // ../../src/core/security/timingSafeCompare.ts
6
+ import { timingSafeEqual } from "crypto";
7
+ function timingSafeCompareString(left, right) {
8
+ const leftBuffer = Buffer.from(left);
9
+ const rightBuffer = Buffer.from(right);
10
+ if (leftBuffer.length !== rightBuffer.length) {
11
+ return false;
12
+ }
13
+ return timingSafeEqual(leftBuffer, rightBuffer);
14
+ }
15
+
16
+ // ../../src/core/security/scimTenantTokens.ts
17
+ function parseScimTenantTokens(raw) {
18
+ const tokens = new Map;
19
+ if (!raw?.trim()) {
20
+ return tokens;
21
+ }
22
+ for (const entry of raw.split(",")) {
23
+ const [tenantPart, tokenPart] = entry.split(":");
24
+ if (!tenantPart || !tokenPart) {
25
+ continue;
26
+ }
27
+ const tenantId = Number.parseInt(tenantPart.trim(), 10);
28
+ const token = tokenPart.trim();
29
+ if (Number.isInteger(tenantId) && tenantId > 0 && token.length > 0) {
30
+ tokens.set(tenantId, token);
31
+ }
32
+ }
33
+ return tokens;
34
+ }
35
+ function resolveScimTenantFromToken(token) {
36
+ const tenantTokens = parseScimTenantTokens(process.env.SCIM_TENANT_TOKENS);
37
+ for (const [tenantId, expectedToken] of tenantTokens) {
38
+ if (timingSafeCompareString(token, expectedToken)) {
39
+ return tenantId;
40
+ }
41
+ }
42
+ const fallbackToken = process.env.SCIM_BEARER_TOKEN ?? TEST_SCIM_BEARER_TOKEN;
43
+ if (timingSafeCompareString(token, fallbackToken)) {
44
+ return 1;
45
+ }
46
+ return null;
47
+ }
48
+ export {
49
+ resolveScimTenantFromToken,
50
+ parseScimTenantTokens
51
+ };
@@ -0,0 +1,14 @@
1
+ // @bun
2
+ // ../../src/core/security/timingSafeCompare.ts
3
+ import { timingSafeEqual } from "crypto";
4
+ function timingSafeCompareString(left, right) {
5
+ const leftBuffer = Buffer.from(left);
6
+ const rightBuffer = Buffer.from(right);
7
+ if (leftBuffer.length !== rightBuffer.length) {
8
+ return false;
9
+ }
10
+ return timingSafeEqual(leftBuffer, rightBuffer);
11
+ }
12
+ export {
13
+ timingSafeCompareString
14
+ };
@@ -0,0 +1,116 @@
1
+ // @bun
2
+ // ../../src/core/database/boundConnection.ts
3
+ var boundConnectionHolder = {
4
+ connection: null
5
+ };
6
+ function bindDatabaseConnection(connection) {
7
+ boundConnectionHolder.connection = connection;
8
+ }
9
+ function getBoundDatabaseConnection() {
10
+ return boundConnectionHolder.connection;
11
+ }
12
+ function resetBoundDatabaseConnection() {
13
+ boundConnectionHolder.connection = null;
14
+ }
15
+
16
+ // ../../src/core/runtime/asyncContextStore.ts
17
+ import { AsyncLocalStorage } from "async_hooks";
18
+ function createAsyncContextStore(key) {
19
+ const symbol = Symbol.for(key);
20
+ const globalRecord = globalThis;
21
+ const existing = globalRecord[symbol];
22
+ if (existing) {
23
+ return existing;
24
+ }
25
+ const store = new AsyncLocalStorage;
26
+ globalRecord[symbol] = store;
27
+ return store;
28
+ }
29
+
30
+ // ../../src/core/database/connectionContext.ts
31
+ var activeConnection = createAsyncContextStore("@getstrata/databaseConnectionContext");
32
+ function runWithDatabaseConnection(connection, callback) {
33
+ return activeConnection.run(connection, callback);
34
+ }
35
+ function getActiveDatabaseConnection(fallback) {
36
+ return activeConnection.getStore() ?? fallback;
37
+ }
38
+ function hasActiveDatabaseConnection() {
39
+ return activeConnection.getStore() !== undefined;
40
+ }
41
+
42
+ // ../../src/core/database/queryProxy.ts
43
+ var POOL_CONNECTION_METHODS = new Set(["begin", "close", "connect"]);
44
+ function createDatabaseQueryProxy(pool) {
45
+ function resolveDatabase() {
46
+ return getActiveDatabaseConnection(pool);
47
+ }
48
+ function resolveDatabaseForProperty(property) {
49
+ if (typeof property === "string" && POOL_CONNECTION_METHODS.has(property)) {
50
+ return pool;
51
+ }
52
+ return resolveDatabase();
53
+ }
54
+ return new Proxy(function database() {}, {
55
+ apply(_target, _thisArg, args) {
56
+ return resolveDatabase()(...args);
57
+ },
58
+ get(_target, property) {
59
+ const connection = resolveDatabaseForProperty(property);
60
+ const value = connection[property];
61
+ return typeof value === "function" ? value.bind(connection) : value;
62
+ }
63
+ });
64
+ }
65
+
66
+ // ../../src/core/database/defaultConnection.ts
67
+ var defaultPool = {
68
+ connection: null
69
+ };
70
+ var defaultQuery = {
71
+ connection: null
72
+ };
73
+ function registerDefaultDatabasePool(connection) {
74
+ defaultPool.connection = connection;
75
+ defaultQuery.connection = createDatabaseQueryProxy(connection);
76
+ }
77
+ function getDefaultDatabasePool() {
78
+ if (!defaultPool.connection) {
79
+ throw new Error("Default database pool is not registered. Call registerDefaultDatabasePool() during app bootstrap.");
80
+ }
81
+ return defaultPool.connection;
82
+ }
83
+ function getDefaultDatabaseQuery() {
84
+ if (!defaultQuery.connection) {
85
+ throw new Error("Default database query handle is not registered. Call registerDefaultDatabasePool() during app bootstrap.");
86
+ }
87
+ return defaultQuery.connection;
88
+ }
89
+
90
+ // ../../src/core/database/repositoryConnection.ts
91
+ function resolveRepositoryConnection() {
92
+ return getBoundDatabaseConnection() ?? getDefaultDatabaseQuery();
93
+ }
94
+ var repositoryConnection = new Proxy(function repositoryConnection2() {}, {
95
+ apply(_target, _thisArg, args) {
96
+ return resolveRepositoryConnection()(...args);
97
+ },
98
+ get(_target, property) {
99
+ const connection = resolveRepositoryConnection();
100
+ const value = connection[property];
101
+ return typeof value === "function" ? value.bind(connection) : value;
102
+ }
103
+ });
104
+
105
+ // ../../src/core/tenant/databaseTenantContext.ts
106
+ async function runWithMigrationBypass(callback) {
107
+ await repositoryConnection`SELECT set_config('app.bypass_rls', 'true', false)`;
108
+ try {
109
+ return await callback();
110
+ } finally {
111
+ await repositoryConnection`SELECT set_config('app.bypass_rls', 'false', false)`;
112
+ }
113
+ }
114
+ export {
115
+ runWithMigrationBypass
116
+ };