@getstrata/core 2.2.59 → 3.0.3

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 (330) hide show
  1. package/CHANGELOG.md +27 -0
  2. package/dist/core/audit/exportAuditLogs.d.ts +12 -3
  3. package/dist/core/audit/exportStore.d.ts +6 -2
  4. package/dist/core/audit/siemFormatter.d.ts +2 -2
  5. package/dist/core/auth/abilityCatalog.d.ts +1 -9
  6. package/dist/core/auth/authContext.d.ts +2 -0
  7. package/dist/core/auth/authOutcome.d.ts +32 -0
  8. package/dist/core/auth/authReader.d.ts +22 -0
  9. package/dist/core/auth/basicAuthGuard.d.ts +19 -3
  10. package/dist/core/auth/emailVerification.d.ts +1 -1
  11. package/dist/core/auth/guard.d.ts +27 -6
  12. package/dist/core/auth/intendedUrlCookie.d.ts +13 -7
  13. package/dist/core/auth/jwt.d.ts +5 -4
  14. package/dist/core/auth/jwtGuard.d.ts +7 -6
  15. package/dist/core/auth/membershipContext.d.ts +10 -7
  16. package/dist/core/auth/membershipContextMiddleware.d.ts +3 -3
  17. package/dist/core/auth/membershipMiddleware.d.ts +1 -2
  18. package/dist/core/auth/membershipServiceImplementation.d.ts +1 -1
  19. package/dist/core/auth/oauth/oidcIdToken.d.ts +25 -16
  20. package/dist/core/auth/oauth/oidcProvider.d.ts +6 -4
  21. package/dist/core/auth/oauth/providers.d.ts +3 -1
  22. package/dist/core/auth/oneTimeToken.d.ts +2 -3
  23. package/dist/core/auth/passwordConfirmCookie.d.ts +15 -6
  24. package/dist/core/auth/passwordLogin.d.ts +5 -5
  25. package/dist/core/auth/pendingMfaCookie.d.ts +2 -2
  26. package/dist/core/auth/policy.d.ts +23 -10
  27. package/dist/core/auth/requireAuthCapability.d.ts +3 -0
  28. package/dist/core/auth/resolveMembershipService.d.ts +3 -2
  29. package/dist/core/auth/saml/samlAssertionReplay.d.ts +4 -4
  30. package/dist/core/auth/saml/samlServiceProvider.d.ts +11 -7
  31. package/dist/core/auth/scimAuthMiddleware.d.ts +10 -3
  32. package/dist/core/auth/sessionCookie.d.ts +20 -9
  33. package/dist/core/auth/sessionGuard.d.ts +14 -3
  34. package/dist/core/cache/createCacheStore.d.ts +6 -3
  35. package/dist/core/cache/redisCacheStore.d.ts +5 -1
  36. package/dist/core/cache/repository.d.ts +5 -1
  37. package/dist/core/cache/simpleCache.d.ts +2 -1
  38. package/dist/core/cache/tokens.d.ts +8 -0
  39. package/dist/core/config/applicationConfig.d.ts +21 -0
  40. package/dist/core/config/configSnapshot.d.ts +3 -0
  41. package/dist/core/config/envSchema.d.ts +3 -2
  42. package/dist/core/contracts/application.d.ts +153 -0
  43. package/dist/core/contracts/authUserDirectory.d.ts +24 -7
  44. package/dist/core/contracts/container.d.ts +20 -23
  45. package/dist/core/contracts/di.d.ts +4 -2
  46. package/dist/core/contracts/executionContext.d.ts +5 -0
  47. package/dist/core/contracts/executionOperations.d.ts +10 -0
  48. package/dist/core/contracts/executionOwnership.d.ts +38 -0
  49. package/dist/core/contracts/persistence.d.ts +20 -0
  50. package/dist/core/contracts/serviceTokens.d.ts +32 -18
  51. package/dist/core/contracts/services.d.ts +63 -0
  52. package/dist/core/contracts/token.d.ts +19 -0
  53. package/dist/core/crypto/fieldEncryption.d.ts +19 -7
  54. package/dist/core/crypto/fieldEncryptionRotation.d.ts +21 -5
  55. package/dist/core/crypto/mfaSecret.d.ts +10 -3
  56. package/dist/core/database/baseRepository.d.ts +14 -10
  57. package/dist/core/database/bindings.d.ts +6 -0
  58. package/dist/core/database/bunSql.d.ts +3 -12
  59. package/dist/core/database/definitions.d.ts +209 -0
  60. package/dist/core/database/dialect.d.ts +5 -24
  61. package/dist/core/database/driverPorts.d.ts +116 -0
  62. package/dist/core/database/errors.d.ts +47 -7
  63. package/dist/core/database/factory.d.ts +51 -31
  64. package/dist/core/database/index.d.ts +9 -10
  65. package/dist/core/database/keyset.d.ts +2 -1
  66. package/dist/core/database/legacyNativeTransaction.d.ts +5 -0
  67. package/dist/core/database/manager.d.ts +12 -0
  68. package/dist/core/database/model.d.ts +91 -97
  69. package/dist/core/database/modelQuery.d.ts +9 -5
  70. package/dist/core/database/modelRegistry.d.ts +52 -33
  71. package/dist/core/database/mysqlConnection.d.ts +1 -19
  72. package/dist/core/database/mysqlNative.d.ts +38 -0
  73. package/dist/core/database/nativeTransactions.d.ts +16 -0
  74. package/dist/core/database/ormInternal.d.ts +85 -0
  75. package/dist/core/database/ormRuntime.d.ts +4 -0
  76. package/dist/core/database/ownedReadOnlyObservation.d.ts +16 -0
  77. package/dist/core/database/postgresNative.d.ts +11 -0
  78. package/dist/core/database/query.d.ts +24 -23
  79. package/dist/core/database/queryPlanSnapshot.d.ts +7 -0
  80. package/dist/core/database/rawMysql.d.ts +7 -0
  81. package/dist/core/database/rawPostgres.d.ts +23 -0
  82. package/dist/core/database/rawSqlite.d.ts +6 -0
  83. package/dist/core/database/relationQueries.d.ts +3 -2
  84. package/dist/core/database/relationQuery.d.ts +24 -6
  85. package/dist/core/database/repositoryQuery.d.ts +6 -1
  86. package/dist/core/database/schema/driver.d.ts +1 -1
  87. package/dist/core/database/seeders/types.d.ts +1 -1
  88. package/dist/core/database/session.d.ts +13 -0
  89. package/dist/core/database/sessionFactory.d.ts +9 -0
  90. package/dist/core/database/sqlDialects.d.ts +22 -0
  91. package/dist/core/database/tokens.d.ts +7 -0
  92. package/dist/core/database/transactionSession.d.ts +43 -0
  93. package/dist/core/errors/http.d.ts +4 -1
  94. package/dist/core/events/{eventBus.d.ts → eventBusClass.d.ts} +1 -3
  95. package/dist/core/events/index.d.ts +2 -3
  96. package/dist/core/events/outbox/index.d.ts +44 -13
  97. package/dist/core/events/outbox/metrics.d.ts +4 -4
  98. package/dist/core/events/outbox/workerTransport.d.ts +17 -0
  99. package/dist/core/http/authMiddleware.d.ts +2 -2
  100. package/dist/core/http/authorizeMiddleware.d.ts +2 -2
  101. package/dist/core/http/bodySizeLimitMiddleware.d.ts +1 -1
  102. package/dist/core/http/conditionalResponse.d.ts +7 -2
  103. package/dist/core/http/contentSecurityPolicy.d.ts +4 -3
  104. package/dist/core/http/corsMiddleware.d.ts +2 -1
  105. package/dist/core/http/csrfMiddleware.d.ts +6 -1
  106. package/dist/core/http/csrfToken.d.ts +17 -7
  107. package/dist/core/http/databaseError.d.ts +4 -0
  108. package/dist/core/http/etag.d.ts +5 -2
  109. package/dist/core/http/flashMiddleware.d.ts +1 -1
  110. package/dist/core/http/flashSession.d.ts +13 -7
  111. package/dist/core/http/index.d.ts +1 -1
  112. package/dist/core/http/loginThrottleMiddleware.d.ts +3 -3
  113. package/dist/core/http/memoryThrottleMiddleware.d.ts +2 -2
  114. package/dist/core/http/parseMultipartUpload.d.ts +3 -2
  115. package/dist/core/http/requestMetaContext.d.ts +5 -0
  116. package/dist/core/http/requireAbilityMiddleware.d.ts +1 -1
  117. package/dist/core/http/requireAuthMiddleware.d.ts +2 -2
  118. package/dist/core/http/requirePasswordConfirmMiddleware.d.ts +2 -1
  119. package/dist/core/http/requireVerifiedMiddleware.d.ts +2 -2
  120. package/dist/core/http/requireWebAuthMiddleware.d.ts +2 -2
  121. package/dist/core/http/response.d.ts +4 -3
  122. package/dist/core/http/scimThrottleMiddleware.d.ts +4 -3
  123. package/dist/core/http/securedRouteModelBinding.d.ts +10 -3
  124. package/dist/core/http/securityHeadersMiddleware.d.ts +1 -2
  125. package/dist/core/http/signedUrl.d.ts +8 -6
  126. package/dist/core/http/throttleMiddleware.d.ts +9 -5
  127. package/dist/core/http/uploads.d.ts +9 -3
  128. package/dist/core/http/webErrorResponse.d.ts +8 -2
  129. package/dist/core/jobs/exportAuditLogsJob.d.ts +5 -2
  130. package/dist/core/jobs/invalidateCacheTagsJob.d.ts +5 -4
  131. package/dist/core/lifecycle/gracefulShutdown.d.ts +2 -5
  132. package/dist/core/logging/requestLoggingMiddleware.d.ts +1 -1
  133. package/dist/core/mail/mailer.d.ts +7 -5
  134. package/dist/core/openapi/generator.d.ts +12 -4
  135. package/dist/core/openapi/registeredRoute.d.ts +4 -4
  136. package/dist/core/queue/createAppQueue.d.ts +9 -4
  137. package/dist/core/queue/failedJobMetrics.d.ts +11 -2
  138. package/dist/core/queue/failedJobRepository.d.ts +6 -3
  139. package/dist/core/queue/failedJobService.d.ts +1 -0
  140. package/dist/core/queue/index.d.ts +16 -6
  141. package/dist/core/queue/jobRegistry.d.ts +3 -2
  142. package/dist/core/queue/jobRunner.d.ts +10 -4
  143. package/dist/core/queue/publicQueue.d.ts +18 -9
  144. package/dist/core/queue/queueConfig.d.ts +20 -10
  145. package/dist/core/queue/queueHandoff.d.ts +31 -0
  146. package/dist/core/queue/queueMetrics.d.ts +10 -3
  147. package/dist/core/queue/queueServices.d.ts +28 -0
  148. package/dist/core/queue/queueWorkerTransport.d.ts +28 -0
  149. package/dist/core/queue/redisQueue.d.ts +19 -10
  150. package/dist/core/queue/redisQueueKeys.d.ts +5 -5
  151. package/dist/core/queue/redisStreams.d.ts +17 -10
  152. package/dist/core/queue/resilientQueue.d.ts +10 -4
  153. package/dist/core/queue/types.d.ts +1 -0
  154. package/dist/core/runtime/appKeyPrefix.d.ts +5 -5
  155. package/dist/core/runtime/application.d.ts +7 -0
  156. package/dist/core/runtime/executionContext.d.ts +9 -0
  157. package/dist/core/runtime/executionTasks.d.ts +49 -0
  158. package/dist/core/runtime/resourceJournal.d.ts +67 -0
  159. package/dist/core/runtime/serviceGraph.d.ts +14 -0
  160. package/dist/core/security/oauthState.d.ts +13 -9
  161. package/dist/core/security/publicReads.d.ts +2 -2
  162. package/dist/core/security/safeFetch.d.ts +1 -0
  163. package/dist/core/security/safeUrl.d.ts +3 -0
  164. package/dist/core/security/scimTenantTokens.d.ts +1 -1
  165. package/dist/core/security/tokenExpiry.d.ts +1 -1
  166. package/dist/core/security/webhookSignature.d.ts +1 -1
  167. package/dist/core/storage/storage.d.ts +24 -16
  168. package/dist/core/tenant/databaseTenantContext.d.ts +5 -7
  169. package/dist/core/tenant/resolveTenant.d.ts +2 -2
  170. package/dist/core/tenant/scopedDatabasePolicy.d.ts +8 -0
  171. package/dist/core/tenant/tenantDatabaseScope.d.ts +3 -7
  172. package/dist/core/tenant/tenantMiddleware.d.ts +15 -4
  173. package/dist/core/tracing/otel.d.ts +4 -6
  174. package/dist/core/tracing/tracingMiddleware.d.ts +3 -3
  175. package/dist/core/view/etaViewEngine.d.ts +1 -1
  176. package/dist/core/view/index.d.ts +5 -4
  177. package/dist/core/view/tokens.d.ts +8 -0
  178. package/dist/core/view/viewRenderer.d.ts +2 -2
  179. package/dist/core/view/webErrorView.d.ts +8 -7
  180. package/dist/core/view/webLayoutData.d.ts +6 -4
  181. package/dist/entries/audit/exportAuditLogs.js +87 -1024
  182. package/dist/entries/audit/siemFormatter.js +4 -90
  183. package/dist/entries/auth/abilityCatalog.js +28 -0
  184. package/dist/entries/auth/accessControl.js +5 -16
  185. package/dist/entries/auth/accountStateMigration.js +216 -236
  186. package/dist/entries/auth/authOutcome.js +80 -0
  187. package/dist/entries/auth/authReader.js +68 -0
  188. package/dist/entries/auth/basicAuthGuard.js +144 -1249
  189. package/dist/entries/auth/emailVerification.js +2 -2
  190. package/dist/entries/auth/intendedUrlCookie.js +35 -59
  191. package/dist/entries/auth/jwt.js +22 -47
  192. package/dist/entries/auth/jwtGuard.js +99 -231
  193. package/dist/entries/auth/membershipMiddleware.js +71 -10
  194. package/dist/entries/auth/membershipScope.js +16 -22
  195. package/dist/entries/auth/membershipService.js +11 -28
  196. package/dist/entries/auth/oauth/oidcProvider.js +59 -64
  197. package/dist/entries/auth/oauth/providers.js +12 -95
  198. package/dist/entries/auth/oauth/samlProvider.js +53 -1080
  199. package/dist/entries/auth/oneTimeToken.js +27 -289
  200. package/dist/entries/auth/passwordConfirmCookie.js +40 -63
  201. package/dist/entries/auth/passwordLogin.js +94 -399
  202. package/dist/entries/auth/pendingMfaCookie.js +6 -6
  203. package/dist/entries/auth/policy.js +22 -56
  204. package/dist/entries/auth/saml/samlServiceProvider.js +55 -1084
  205. package/dist/entries/auth/scimAuthMiddleware.js +16 -3358
  206. package/dist/entries/auth/sessionCookie.js +58 -73
  207. package/dist/entries/auth/sessionGuard.js +95 -248
  208. package/dist/entries/auth/tokenHash.js +11 -43
  209. package/dist/entries/cache/createCacheStore.js +126 -117
  210. package/dist/entries/cache/repository.js +25 -0
  211. package/dist/entries/cache/simpleCache.js +12 -7
  212. package/dist/entries/cache/tokens.js +9 -0
  213. package/dist/entries/config/applicationConfig.js +163 -0
  214. package/dist/entries/config/envSchema.js +21 -4
  215. package/dist/entries/contracts/application.js +1 -0
  216. package/dist/entries/contracts/authUserDirectory.js +10 -0
  217. package/dist/entries/contracts/container.js +99 -26
  218. package/dist/entries/contracts/di.js +3 -0
  219. package/dist/entries/contracts/executionContext.js +7 -0
  220. package/dist/entries/contracts/executionOperations.js +7 -0
  221. package/dist/entries/contracts/executionOwnership.js +7 -0
  222. package/dist/entries/contracts/membership.js +1 -0
  223. package/dist/entries/contracts/persistence.js +1 -0
  224. package/dist/entries/contracts/serviceTokens.js +26 -116
  225. package/dist/entries/contracts/services.js +98 -0
  226. package/dist/entries/contracts/token.js +41 -0
  227. package/dist/entries/crypto/fieldEncryption.js +49 -50
  228. package/dist/entries/crypto/mfaSecret.js +86 -82
  229. package/dist/entries/database/acquisitionMetrics.js +107 -0
  230. package/dist/entries/database/baseRepository.d.ts +2 -0
  231. package/dist/entries/database/bindings.js +2082 -0
  232. package/dist/entries/database/definitions.js +175 -0
  233. package/dist/entries/database/errors.js +114 -89
  234. package/dist/entries/database/factory.js +67 -28
  235. package/dist/entries/database/migrations.js +172 -224
  236. package/dist/entries/database/model.d.ts +1 -0
  237. package/dist/entries/database/ownedReadOnlyObservation.js +1282 -0
  238. package/dist/entries/database/query.js +159 -161
  239. package/dist/entries/database/repositoryQuery.d.ts +1 -0
  240. package/dist/entries/database/repositoryQuery.js +1 -1373
  241. package/dist/entries/database/schema.js +216 -236
  242. package/dist/entries/database/session.js +1 -0
  243. package/dist/entries/database/sqliteConnection.js +525 -83
  244. package/dist/entries/database/tokens.js +9 -0
  245. package/dist/entries/errors/http.js +118 -1
  246. package/dist/entries/http/authMiddleware.js +8 -5
  247. package/dist/entries/http/authorizeMiddleware.js +1 -1
  248. package/dist/entries/http/bodySizeLimitMiddleware.js +2 -2
  249. package/dist/entries/http/clientIp.js +2 -2
  250. package/dist/entries/http/conditionalResponse.js +19 -7
  251. package/dist/entries/http/corsMiddleware.js +6 -101
  252. package/dist/entries/http/csrfMiddleware.js +92 -106
  253. package/dist/entries/http/csrfToken.js +58 -94
  254. package/dist/entries/http/etag.js +7 -4
  255. package/dist/entries/http/flashMiddleware.js +57 -99
  256. package/dist/entries/http/flashSession.js +41 -68
  257. package/dist/entries/http/memoryThrottleMiddleware.js +43 -186
  258. package/dist/entries/http/metricsMiddleware.js +2 -16
  259. package/dist/entries/http/parseMultipartUpload.js +15 -29
  260. package/dist/entries/http/requireAbilityMiddleware.js +2 -2
  261. package/dist/entries/http/requirePasswordConfirmMiddleware.js +19 -31
  262. package/dist/entries/http/requireVerifiedMiddleware.js +4 -7
  263. package/dist/entries/http/requireWebAuthMiddleware.js +2 -2
  264. package/dist/entries/http/response.js +67 -233
  265. package/dist/entries/http/routeMiddleware.js +0 -14
  266. package/dist/entries/http/scimThrottleMiddleware.js +43 -237
  267. package/dist/entries/http/securedRouteModelBinding.js +37 -25
  268. package/dist/entries/http/securityHeadersMiddleware.js +8 -25
  269. package/dist/entries/http/signedUrl.js +20 -110
  270. package/dist/entries/http/throttleMiddleware.js +41 -185
  271. package/dist/entries/http/uploads.js +9 -24
  272. package/dist/entries/jobs/exportAuditLogsJob.js +17 -1498
  273. package/dist/entries/jobs/invalidateCacheTagsJob.js +12 -47
  274. package/dist/entries/logging/requestLoggingMiddleware.js +4 -4
  275. package/dist/entries/mail/mailer.js +68 -78
  276. package/dist/entries/openapi/generator.js +33 -100
  277. package/dist/entries/queue/createAppQueue.js +416 -254
  278. package/dist/entries/queue/failedJobRepository.js +19 -8
  279. package/dist/entries/queue/failedJobService.js +1 -0
  280. package/dist/entries/queue/jobRunner.js +141 -66
  281. package/dist/entries/queue/publicQueue.js +411 -255
  282. package/dist/entries/queue/queueConfig.js +61 -0
  283. package/dist/entries/queue/queueHandoff.js +318 -0
  284. package/dist/entries/queue/queueMetrics.js +989 -1384
  285. package/dist/entries/queue/queueServices.js +133 -0
  286. package/dist/entries/queue/queueWorkerTransport.js +1703 -0
  287. package/dist/entries/queue/redisQueue.js +282 -180
  288. package/dist/entries/queue.js +6 -45
  289. package/dist/entries/runtime/application.js +1585 -0
  290. package/dist/entries/runtime/asyncContextStore.js +0 -16
  291. package/dist/entries/security/oauthState.js +35 -67
  292. package/dist/entries/security/publicReads.js +4 -4
  293. package/dist/entries/security/safeFetch.js +1 -0
  294. package/dist/entries/security/scimTenantTokens.js +3 -3
  295. package/dist/entries/security/tokenExpiry.js +2 -2
  296. package/dist/entries/security/totp.js +1 -87
  297. package/dist/entries/security/webhookSignature.js +2 -90
  298. package/dist/entries/storage/storage.js +120 -45
  299. package/dist/entries/tenant/databaseTenantContext.js +6 -907
  300. package/dist/entries/tenant/publicTenantHost.js +78 -0
  301. package/dist/entries/tenant/resolveTenant.js +14 -0
  302. package/dist/entries/tenant/scopedDatabasePolicy.js +75 -0
  303. package/dist/entries/tenant/tenancyConfig.js +1 -19
  304. package/dist/entries/tenant/tenantDatabaseScope.js +3 -892
  305. package/dist/entries/tracing/tracingMiddleware.js +104 -173
  306. package/dist/entries/view/tokens.js +11 -0
  307. package/dist/framework/public-api.d.ts +62 -44
  308. package/dist/index.js +10433 -11347
  309. package/dist/internal/ormInternal.js +117 -0
  310. package/dist/internal/ormRuntime.js +5000 -0
  311. package/package.json +158 -46
  312. package/dist/core/database/bindConnection.d.ts +0 -1
  313. package/dist/core/database/boundConnection.d.ts +0 -5
  314. package/dist/core/database/defaultConnection.d.ts +0 -7
  315. package/dist/core/database/namedConnections.d.ts +0 -15
  316. package/dist/core/database/readOnlyCollector.d.ts +0 -7
  317. package/dist/core/database/repositoryConnection.d.ts +0 -4
  318. package/dist/core/database/transaction.d.ts +0 -23
  319. package/dist/core/database/transactionControl.d.ts +0 -6
  320. package/dist/core/events/deferredModelEvents.d.ts +0 -7
  321. package/dist/core/facades/index.d.ts +0 -10
  322. package/dist/core/runtime/applicationRegistry.d.ts +0 -18
  323. package/dist/entries/database/bindConnection.js +0 -1
  324. package/dist/entries/database/boundConnection.js +0 -1
  325. package/dist/entries/database/defaultConnection.js +0 -1
  326. package/dist/entries/database/namedConnections.js +0 -1
  327. package/dist/entries/database/repositoryConnection.js +0 -1
  328. package/dist/entries/database/transaction.js +0 -1
  329. package/dist/entries/facades.js +0 -711
  330. package/dist/entries/runtime/applicationRegistry.js +0 -1
@@ -1,913 +1,4 @@
1
1
  // @bun
2
- var __esm = (fn, res, err) => () => {
3
- if (fn)
4
- try {
5
- res = fn(fn = 0);
6
- } catch (e) {
7
- err = [e];
8
- }
9
- if (err)
10
- throw err[0];
11
- return res;
12
- };
13
-
14
- // ../../src/core/runtime/asyncContextStore.ts
15
- import { AsyncLocalStorage } from "async_hooks";
16
- function createAsyncContextStore(key) {
17
- const symbol = Symbol.for(key);
18
- const globalRecord = globalThis;
19
- const existing = globalRecord[symbol];
20
- if (existing) {
21
- return existing;
22
- }
23
- const store = new AsyncLocalStorage;
24
- globalRecord[symbol] = store;
25
- return store;
26
- }
27
- var init_asyncContextStore = () => {};
28
-
29
- // ../../src/core/database/schema/driver.ts
30
- function normalizeConnectionName(connection) {
31
- const normalized = connection.trim().toLowerCase();
32
- if (normalized === "pgsql" || normalized === "postgres" || normalized === "postgresql") {
33
- return "pgsql";
34
- }
35
- if (normalized === "mysql" || normalized === "mariadb") {
36
- return "mysql";
37
- }
38
- if (normalized === "sqlite") {
39
- return "sqlite";
40
- }
41
- throw new Error(`Unsupported DB_CONNECTION: ${connection}`);
42
- }
43
- function resolveDriverFromUrl(url) {
44
- const normalized = url.trim().toLowerCase();
45
- if (normalized.startsWith("postgres://") || normalized.startsWith("postgresql://") || normalized.startsWith("postgres:")) {
46
- return "pgsql";
47
- }
48
- if (normalized.startsWith("mysql://") || normalized.startsWith("mysql:")) {
49
- return "mysql";
50
- }
51
- if (normalized.startsWith("sqlite:")) {
52
- return "sqlite";
53
- }
54
- return null;
55
- }
56
- function resolveDatabaseDriver(options = {}) {
57
- const connection = options.connection ?? process.env.DB_CONNECTION;
58
- if (connection) {
59
- return normalizeConnectionName(connection);
60
- }
61
- const url = options.url ?? process.env.DATABASE_URL ?? "";
62
- const fromUrl = resolveDriverFromUrl(url);
63
- if (fromUrl) {
64
- return fromUrl;
65
- }
66
- return "pgsql";
67
- }
68
- var init_driver = () => {};
69
-
70
- // ../../src/core/database/dialect.ts
71
- function assertSafeIdentifier(identifier) {
72
- if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(identifier)) {
73
- throw new Error(`Invalid SQL identifier: ${identifier}`);
74
- }
75
- return identifier;
76
- }
77
- function quoteIdentifierFor(dialect, column) {
78
- return dialect.quoteIdentifier(column);
79
- }
80
- function dialectFor(driver) {
81
- return dialects[driver];
82
- }
83
- function currentSqlDialect() {
84
- return dialectContext.getStore() ?? dialectOverride ?? dialectFor(resolveDatabaseDriver());
85
- }
86
- var postgresDialect, mysqlDialect, sqliteDialect, dialects, dialectContext, dialectOverride = null;
87
- var init_dialect = __esm(() => {
88
- init_asyncContextStore();
89
- init_driver();
90
- postgresDialect = {
91
- driver: "pgsql",
92
- placeholder(index) {
93
- return `$${index}`;
94
- },
95
- quoteIdentifier(identifier) {
96
- return `"${assertSafeIdentifier(identifier)}"`;
97
- },
98
- nowExpression() {
99
- return "NOW()";
100
- },
101
- epochMillisecondsExpression() {
102
- return "CAST(EXTRACT(EPOCH FROM clock_timestamp()) * 1000 AS BIGINT)";
103
- },
104
- rowLockClause(skipLocked = false) {
105
- return ` FOR UPDATE${skipLocked ? " SKIP LOCKED" : ""}`;
106
- },
107
- timestampValue(value) {
108
- return value.toISOString();
109
- },
110
- returningClause(columns) {
111
- return ` RETURNING ${columns}`;
112
- },
113
- ilikeOperator() {
114
- return "ILIKE";
115
- },
116
- nullsLastSuffix() {
117
- return " NULLS LAST";
118
- },
119
- castToText(expression) {
120
- return `${expression}::text`;
121
- },
122
- upsertSuffix(conflictColumns, updateColumns) {
123
- const target = conflictColumns.map((column) => quoteIdentifierFor(this, column)).join(", ");
124
- if (updateColumns.length === 0) {
125
- return ` ON CONFLICT (${target}) DO NOTHING`;
126
- }
127
- const assignments = updateColumns.map((column) => {
128
- const quoted = quoteIdentifierFor(this, column);
129
- return `${quoted} = excluded.${quoted}`;
130
- }).join(", ");
131
- return ` ON CONFLICT (${target}) DO UPDATE SET ${assignments}`;
132
- }
133
- };
134
- mysqlDialect = {
135
- driver: "mysql",
136
- placeholder() {
137
- return "?";
138
- },
139
- quoteIdentifier(identifier) {
140
- return `\`${assertSafeIdentifier(identifier)}\``;
141
- },
142
- nowExpression() {
143
- return "CURRENT_TIMESTAMP";
144
- },
145
- epochMillisecondsExpression() {
146
- return "CAST(UNIX_TIMESTAMP(CURRENT_TIMESTAMP(3)) * 1000 AS UNSIGNED)";
147
- },
148
- rowLockClause(skipLocked = false) {
149
- return ` FOR UPDATE${skipLocked ? " SKIP LOCKED" : ""}`;
150
- },
151
- timestampValue(value) {
152
- return value.toISOString().slice(0, 19).replace("T", " ");
153
- },
154
- returningClause() {
155
- return "";
156
- },
157
- ilikeOperator() {
158
- return "LIKE";
159
- },
160
- nullsLastSuffix() {
161
- return "";
162
- },
163
- castToText(expression) {
164
- return `CAST(${expression} AS CHAR)`;
165
- },
166
- upsertSuffix(conflictColumns, updateColumns) {
167
- if (updateColumns.length === 0) {
168
- const anchor = quoteIdentifierFor(this, conflictColumns[0] ?? "");
169
- return ` ON DUPLICATE KEY UPDATE ${anchor} = ${anchor}`;
170
- }
171
- const assignments = updateColumns.map((column) => {
172
- const quoted = quoteIdentifierFor(this, column);
173
- return `${quoted} = VALUES(${quoted})`;
174
- }).join(", ");
175
- return ` ON DUPLICATE KEY UPDATE ${assignments}`;
176
- }
177
- };
178
- sqliteDialect = {
179
- driver: "sqlite",
180
- placeholder() {
181
- return "?";
182
- },
183
- quoteIdentifier(identifier) {
184
- return `"${assertSafeIdentifier(identifier)}"`;
185
- },
186
- nowExpression() {
187
- return "strftime('%Y-%m-%dT%H:%M:%fZ', 'now')";
188
- },
189
- epochMillisecondsExpression() {
190
- return "CAST((julianday('now') - 2440587.5) * 86400000 AS INTEGER)";
191
- },
192
- rowLockClause() {
193
- return "";
194
- },
195
- timestampValue(value) {
196
- return value.toISOString();
197
- },
198
- returningClause(columns) {
199
- return ` RETURNING ${columns}`;
200
- },
201
- ilikeOperator() {
202
- return "LIKE";
203
- },
204
- nullsLastSuffix() {
205
- return "";
206
- },
207
- castToText(expression) {
208
- return `CAST(${expression} AS TEXT)`;
209
- },
210
- upsertSuffix(conflictColumns, updateColumns) {
211
- const target = conflictColumns.map((column) => quoteIdentifierFor(this, column)).join(", ");
212
- if (updateColumns.length === 0) {
213
- return ` ON CONFLICT (${target}) DO NOTHING`;
214
- }
215
- const assignments = updateColumns.map((column) => {
216
- const quoted = quoteIdentifierFor(this, column);
217
- return `${quoted} = excluded.${quoted}`;
218
- }).join(", ");
219
- return ` ON CONFLICT (${target}) DO UPDATE SET ${assignments}`;
220
- }
221
- };
222
- dialects = {
223
- pgsql: postgresDialect,
224
- mysql: mysqlDialect,
225
- sqlite: sqliteDialect
226
- };
227
- dialectContext = createAsyncContextStore("@getstrata/sqlDialect");
228
- });
229
-
230
- // ../../src/core/tenant/tenantContext.ts
231
- function runWithTenant(tenant, callback) {
232
- return tenantContext.run(tenant, callback);
233
- }
234
- function currentTenant() {
235
- return tenantContext.getStore() ?? null;
236
- }
237
- var tenantContext;
238
- var init_tenantContext = __esm(() => {
239
- init_asyncContextStore();
240
- tenantContext = createAsyncContextStore("@getstrata/tenantContext");
241
- });
242
-
243
- // ../../src/core/events/eventBus.ts
244
- class EventBus {
245
- constructor() {}
246
- transactionalListeners = new Map;
247
- listenTransactional(event, listener) {
248
- const handlers = this.transactionalListeners.get(event) ?? new Set;
249
- handlers.add(listener);
250
- this.transactionalListeners.set(event, handlers);
251
- return () => {
252
- handlers.delete(listener);
253
- if (!handlers.size)
254
- this.transactionalListeners.delete(event);
255
- };
256
- }
257
- hasTransactionalListeners(event) {
258
- return (this.transactionalListeners.get(event)?.size ?? 0) > 0;
259
- }
260
- async dispatchTransactional(event, payload) {
261
- for (const listener of this.transactionalListeners.get(event) ?? [])
262
- await listener(payload);
263
- }
264
- listeners = new Map;
265
- on(event, listener) {
266
- return this.listen(event, listener);
267
- }
268
- listen(event, listener) {
269
- const handlers = this.listeners.get(event) ?? new Set;
270
- handlers.add(listener);
271
- this.listeners.set(event, handlers);
272
- return () => {
273
- handlers.delete(listener);
274
- if (handlers.size === 0) {
275
- this.listeners.delete(event);
276
- }
277
- };
278
- }
279
- async emit(event, payload) {
280
- await this.dispatch(event, payload);
281
- }
282
- async dispatch(event, payload) {
283
- const handlers = this.listeners.get(event);
284
- if (!handlers || handlers.size === 0) {
285
- return;
286
- }
287
- for (const handler of handlers) {
288
- await handler(payload);
289
- }
290
- }
291
- }
292
- function readSharedEventBus() {
293
- const globalBus = globalThis[EVENT_BUS_KEY];
294
- if (globalBus) {
295
- return globalBus;
296
- }
297
- const bus = new EventBus;
298
- globalThis[EVENT_BUS_KEY] = bus;
299
- return bus;
300
- }
301
- var EVENT_BUS_KEY, eventBus;
302
- var init_eventBus = __esm(() => {
303
- EVENT_BUS_KEY = Symbol.for("@getstrata/eventBus");
304
- eventBus = readSharedEventBus();
305
- });
306
-
307
- // ../../src/core/database/connectionContext.ts
308
- function runWithDatabaseConnection(connection, callback) {
309
- return activeConnection.run(connection, callback);
310
- }
311
- function getActiveDatabaseConnection(fallback) {
312
- return activeConnection.getStore() ?? fallback;
313
- }
314
- function hasActiveDatabaseConnection() {
315
- return activeConnection.getStore() !== undefined;
316
- }
317
- var activeConnection;
318
- var init_connectionContext = __esm(() => {
319
- init_asyncContextStore();
320
- activeConnection = createAsyncContextStore("@getstrata/databaseConnectionContext");
321
- });
322
-
323
- // ../../src/core/database/transactionControl.ts
324
- function unwrapTransactionRollback(error, depth = 0) {
325
- if (error instanceof TransactionRollback) {
326
- return error;
327
- }
328
- if (depth >= 5 || !(error instanceof Error) || error.cause === undefined) {
329
- return null;
330
- }
331
- return unwrapTransactionRollback(error.cause, depth + 1);
332
- }
333
- function hasActiveTransaction() {
334
- return hasActiveDatabaseConnection() && (transactionScopes.getStore()?.rollback.length ?? 0) > 0;
335
- }
336
- function requestTransactionRollback() {
337
- const state = transactionScopes.getStore();
338
- const index = state ? state.rollback.length - 1 : -1;
339
- if (!state || index < 0) {
340
- return;
341
- }
342
- state.rollback[index] = true;
343
- }
344
- function scopeRequestsRollback() {
345
- const state = transactionScopes.getStore();
346
- if (!state || state.rollback.length === 0) {
347
- return false;
348
- }
349
- return state.rollback[state.rollback.length - 1] === true;
350
- }
351
- async function commitOrRollbackScope(result) {
352
- if (scopeRequestsRollback()) {
353
- throw new TransactionRollback(result);
354
- }
355
- return result;
356
- }
357
- async function settleTransaction(work) {
358
- try {
359
- return await work();
360
- } catch (error) {
361
- const rollback = unwrapTransactionRollback(error);
362
- if (rollback) {
363
- return rollback.result;
364
- }
365
- throw error;
366
- }
367
- }
368
- async function runWithTransactionScope(callback) {
369
- const existing = transactionScopes.getStore();
370
- if (existing) {
371
- existing.rollback.push(false);
372
- try {
373
- return await callback();
374
- } finally {
375
- existing.rollback.pop();
376
- }
377
- }
378
- const state = { rollback: [false] };
379
- return await transactionScopes.run(state, callback);
380
- }
381
- var TransactionRollback, transactionScopes;
382
- var init_transactionControl = __esm(() => {
383
- init_asyncContextStore();
384
- init_connectionContext();
385
- TransactionRollback = class TransactionRollback extends Error {
386
- result;
387
- constructor(result) {
388
- super("Transaction rolled back");
389
- this.name = "TransactionRollback";
390
- this.result = result;
391
- }
392
- };
393
- transactionScopes = createAsyncContextStore("@getstrata/transactionScopes");
394
- });
395
-
396
- // ../../src/core/tenant/tenancyConfig.ts
397
- function readTenancyDriver(env = process.env) {
398
- const raw = env.TENANCY_DRIVER?.trim();
399
- if (raw === undefined || raw === "") {
400
- return "rls";
401
- }
402
- if (TENANCY_DRIVERS.includes(raw)) {
403
- return raw;
404
- }
405
- throw new Error(`TENANCY_DRIVER must be one of ${TENANCY_DRIVERS.join(", ")}; received "${raw}".`);
406
- }
407
- function isTenancyEnabled(env = process.env) {
408
- return readTenancyDriver(env) !== "none";
409
- }
410
- function isRlsTenancy(env = process.env) {
411
- return readTenancyDriver(env) === "rls";
412
- }
413
- var TENANCY_DRIVERS;
414
- var init_tenancyConfig = __esm(() => {
415
- TENANCY_DRIVERS = ["rls", "column", "none"];
416
- });
417
-
418
- // ../../src/core/tenant/databaseTenantContext.ts
419
- import { getDefaultDatabasePool } from "@getstrata/core/database/defaultConnection";
420
- import { AsyncLocalStorage as AsyncLocalStorage2 } from "async_hooks";
421
- async function applyBypassToTransaction(transaction, bypass) {
422
- await transaction.unsafe(`SELECT set_config('app.bypass_rls', $1, true)`, [
423
- bypass ? "true" : "false"
424
- ]);
425
- }
426
- function stringifyBypassIdentifier(identifier) {
427
- if (typeof identifier === "number") {
428
- return String(identifier);
429
- }
430
- return identifier.trim();
431
- }
432
- async function applyIdentifierToTransaction(transaction, identifier) {
433
- await transaction.unsafe(`SELECT set_config('app.bypass_identifier', $1, true)`, [
434
- stringifyBypassIdentifier(identifier)
435
- ]);
436
- }
437
- function assertBypassIdentifier(identifier) {
438
- if (typeof identifier === "number") {
439
- if (!Number.isInteger(identifier) || identifier <= 0) {
440
- throw new Error("RLS bypass requires a caller-supplied identifier that pins the row.");
441
- }
442
- return;
443
- }
444
- if (typeof identifier === "string" && identifier.trim() !== "") {
445
- return;
446
- }
447
- throw new Error("RLS bypass requires a caller-supplied identifier that pins the row.");
448
- }
449
- async function runWithScopedTenantTransaction(apply, callback) {
450
- if (!isRlsTenancy()) {
451
- return await callback();
452
- }
453
- if (hasActiveDatabaseConnection()) {
454
- const connection = getActiveDatabaseConnection(getDefaultDatabasePool());
455
- return await runInTransaction(async () => {
456
- const [previous] = await connection.unsafe(`SELECT current_setting('app.tenant_id', true) AS tenant_id,
457
- current_setting('app.bypass_rls', true) AS bypass_rls,
458
- current_setting('app.bypass_identifier', true) AS bypass_identifier`);
459
- await apply(connection);
460
- const result = await callback();
461
- await connection.unsafe(`SELECT set_config('app.tenant_id', $1, true),
462
- set_config('app.bypass_rls', $2, true), set_config('app.bypass_identifier', $3, true)`, [previous?.tenant_id ?? "", previous?.bypass_rls ?? "", previous?.bypass_identifier ?? ""]);
463
- return result;
464
- });
465
- }
466
- const pool = getDefaultDatabasePool();
467
- const begin = pool.begin;
468
- if (typeof begin !== "function") {
469
- throw new Error("RLS migration bypass requires a pool that supports begin(). Session-scoped set_config is not used on pooled connections.");
470
- }
471
- return await settleTransaction(() => runWithDeferredModelEvents(async () => {
472
- return await begin.bind(pool)(AsyncLocalStorage2.bind(async (transaction) => {
473
- await apply(transaction);
474
- return await runWithDatabaseConnection(transaction, () => runWithTransactionScope(async () => commitOrRollbackScope(await callback())));
475
- }));
476
- }));
477
- }
478
- async function runWithMigrationBypass(callback) {
479
- return await runWithScopedTenantTransaction((transaction) => applyBypassToTransaction(transaction, true), callback);
480
- }
481
- async function runWithMigrationBypassForIdentifier(identifier, callback) {
482
- assertBypassIdentifier(identifier);
483
- return await runWithScopedTenantTransaction((transaction) => applyIdentifierToTransaction(transaction, identifier), callback);
484
- }
485
- var init_databaseTenantContext = __esm(() => {
486
- init_connectionContext();
487
- init_transaction();
488
- init_transactionControl();
489
- init_deferredModelEvents();
490
- init_tenancyConfig();
491
- });
492
-
493
- // ../../src/core/tenant/tenantDatabaseScope.ts
494
- import { getDefaultDatabasePool as getDefaultDatabasePool2 } from "@getstrata/core/database/defaultConnection";
495
- import { AsyncLocalStorage as AsyncLocalStorage3 } from "async_hooks";
496
- async function applyTenantContextToTransaction(transaction, tenantId) {
497
- await transaction.unsafe(`SELECT set_config('app.tenant_id', $1, true)`, [String(tenantId)]);
498
- await transaction.unsafe(`SELECT set_config('app.bypass_rls', $1, true)`, ["false"]);
499
- }
500
- async function runWithTenantDatabase(tenant, callback) {
501
- const outerTenant = currentTenant();
502
- if (hasActiveDatabaseConnection() && outerTenant && outerTenant.id !== tenant.id) {
503
- throw new Error("Cannot switch tenants inside an active database transaction.");
504
- }
505
- if (!isTenancyEnabled() || !isRlsTenancy()) {
506
- return await runWithTenant(tenant, callback);
507
- }
508
- if (hasActiveDatabaseConnection()) {
509
- const activeConnection = getActiveDatabaseConnection(getDefaultDatabasePool2());
510
- return await runWithScopedTenantTransaction(() => applyTenantContextToTransaction(activeConnection, tenant.id), () => runWithTenant(tenant, callback));
511
- }
512
- const pool = getDefaultDatabasePool2();
513
- const begin = pool.begin;
514
- if (typeof begin !== "function") {
515
- throw new Error("RLS tenant scope requires a pool that supports begin(). Session-scoped set_config is not used on pooled connections.");
516
- }
517
- return await settleTransaction(() => runWithDeferredModelEvents(async () => {
518
- return await begin.bind(pool)(AsyncLocalStorage3.bind(async (transaction) => {
519
- await applyTenantContextToTransaction(transaction, tenant.id);
520
- return await runWithDatabaseConnection(transaction, async () => {
521
- return await runWithTransactionScope(async () => commitOrRollbackScope(await runWithTenant(tenant, callback)));
522
- });
523
- }));
524
- }));
525
- }
526
- function isInsideTenantDatabaseScope(tenantId = currentTenant()?.id) {
527
- return hasActiveDatabaseConnection() && currentTenant()?.id === tenantId;
528
- }
529
- var init_tenantDatabaseScope = __esm(() => {
530
- init_connectionContext();
531
- init_transactionControl();
532
- init_deferredModelEvents();
533
- init_databaseTenantContext();
534
- init_tenancyConfig();
535
- init_tenantContext();
536
- });
537
-
538
- // ../../src/core/events/deferredModelEvents.ts
539
- function sameTenant(left, right) {
540
- if (left === null && right === null) {
541
- return true;
542
- }
543
- if (left === null || right === null) {
544
- return false;
545
- }
546
- return left.id === right.id;
547
- }
548
- function groupQueuedModelEvents(queued) {
549
- const groups = [];
550
- for (const item of queued) {
551
- const lastGroup = groups[groups.length - 1];
552
- const last = lastGroup?.[lastGroup.length - 1];
553
- if (!lastGroup || !last || !sameTenant(last.tenant, item.tenant) || "callback" in last !== "callback" in item) {
554
- groups.push([item]);
555
- } else {
556
- lastGroup.push(item);
557
- }
558
- }
559
- return groups;
560
- }
561
- async function dispatchEventBatch(batch) {
562
- for (const item of batch) {
563
- if ("callback" in item)
564
- await item.callback();
565
- else
566
- await eventBus.dispatch(item.event, item.payload);
567
- }
568
- }
569
- async function dispatchQueuedModelEvents(queued) {
570
- if (queued.length === 0) {
571
- return;
572
- }
573
- await Promise.resolve().then(() => init_tenantDatabaseScope());
574
- for (const batch of groupQueuedModelEvents(queued)) {
575
- const tenant = batch[0]?.tenant ?? null;
576
- if (tenant) {
577
- if (batch.some((item) => ("callback" in item))) {
578
- await runWithTenant(tenant, () => dispatchEventBatch(batch));
579
- } else {
580
- await runWithTenantDatabase(tenant, () => dispatchEventBatch(batch));
581
- }
582
- } else {
583
- await dispatchEventBatch(batch);
584
- }
585
- }
586
- }
587
- async function dispatchModelEvent(event, payload) {
588
- await eventBus.dispatchTransactional(event, payload);
589
- const state = deferredModelEvents.getStore();
590
- const frame = state?.frames[state.frames.length - 1];
591
- if (frame) {
592
- frame.push({
593
- event,
594
- payload,
595
- tenant: currentTenant()
596
- });
597
- return;
598
- }
599
- await eventBus.dispatch(event, payload);
600
- }
601
- async function runWithDeferredModelEvents(callback) {
602
- const existing = deferredModelEvents.getStore();
603
- if (existing) {
604
- existing.frames.push([]);
605
- existing.rollbackFrames.push([]);
606
- try {
607
- const result = await callback();
608
- const nested = existing.frames.pop() ?? [];
609
- const rollback = existing.rollbackFrames.pop() ?? [];
610
- existing.rollbackFrames.at(-1)?.push(...rollback);
611
- const parent = existing.frames[existing.frames.length - 1];
612
- if (parent) {
613
- parent.push(...nested);
614
- }
615
- return result;
616
- } catch (error) {
617
- existing.frames.pop();
618
- for (const rollback of (existing.rollbackFrames.pop() ?? []).reverse())
619
- rollback();
620
- throw error;
621
- }
622
- }
623
- const state = { frames: [[]], rollbackFrames: [[]] };
624
- let result;
625
- try {
626
- result = await deferredModelEvents.run(state, callback);
627
- } catch (error) {
628
- for (const rollback of (state.rollbackFrames[0] ?? []).reverse())
629
- rollback();
630
- throw error;
631
- }
632
- await dispatchQueuedModelEvents(state.frames[0] ?? []);
633
- return result;
634
- }
635
- var deferredModelEvents;
636
- var init_deferredModelEvents = __esm(() => {
637
- init_asyncContextStore();
638
- init_tenantContext();
639
- init_eventBus();
640
- deferredModelEvents = createAsyncContextStore("@getstrata/deferredModelEvents");
641
- });
642
-
643
- // ../../src/core/database/acquisitionMetrics.ts
644
- async function observeTransactionAcquisition(metrics, acquire, signal) {
645
- const state = states.get(metrics);
646
- if (!state)
647
- throw new TypeError("Transaction acquisition metrics must be created by the framework factory.");
648
- const started = performance.now();
649
- state.inflight++;
650
- let outcome = "acquired";
651
- try {
652
- return await acquire();
653
- } catch (error) {
654
- outcome = signal?.aborted ? "aborted" : "failed";
655
- throw error;
656
- } finally {
657
- state.inflight--;
658
- const elapsed = Math.max(0, performance.now() - started) / 1000;
659
- const histogram = state.outcomes[outcomes.indexOf(outcome)];
660
- if (histogram) {
661
- histogram.count++;
662
- histogram.sumSeconds += elapsed;
663
- for (let index = 0;index < ACQUISITION_BUCKETS_SECONDS.length; index++) {
664
- const bound = ACQUISITION_BUCKETS_SECONDS[index];
665
- if (bound !== undefined && elapsed <= bound)
666
- histogram.buckets[index] = (histogram.buckets[index] ?? 0) + 1;
667
- }
668
- }
669
- }
670
- }
671
- var ACQUISITION_BUCKETS_SECONDS, outcomes, metricsBrand, states;
672
- var init_acquisitionMetrics = __esm(() => {
673
- ACQUISITION_BUCKETS_SECONDS = [
674
- 0.001,
675
- 0.005,
676
- 0.01,
677
- 0.025,
678
- 0.05,
679
- 0.1,
680
- 0.25,
681
- 0.5,
682
- 1,
683
- 2.5,
684
- 5,
685
- 10
686
- ];
687
- outcomes = ["acquired", "failed", "aborted"];
688
- metricsBrand = Symbol("transaction acquisition metrics");
689
- states = new WeakMap;
690
- });
691
-
692
- // ../../src/core/database/connection.ts
693
- function createDatabaseConnection(source) {
694
- return {
695
- async unsafe(query, params = []) {
696
- return await source.unsafe(query, params);
697
- }
698
- };
699
- }
700
- var init_connection = () => {};
701
-
702
- // ../../src/core/database/boundConnection.ts
703
- function boundConnectionState() {
704
- const globalRecord = globalThis;
705
- const existing = globalRecord[BOUND_CONNECTION_KEY];
706
- if (existing) {
707
- return existing;
708
- }
709
- const created = { connection: null };
710
- globalRecord[BOUND_CONNECTION_KEY] = created;
711
- return created;
712
- }
713
- function getBoundDatabaseConnection() {
714
- return boundConnectionState().connection;
715
- }
716
- var BOUND_CONNECTION_KEY;
717
- var init_boundConnection = __esm(() => {
718
- BOUND_CONNECTION_KEY = Symbol.for("@getstrata/boundDatabaseConnection");
719
- });
720
-
721
- // ../../src/core/database/queryProxy.ts
722
- var POOL_CONNECTION_METHODS;
723
- var init_queryProxy = __esm(() => {
724
- init_connectionContext();
725
- POOL_CONNECTION_METHODS = new Set(["begin", "close", "connect"]);
726
- });
727
-
728
- // ../../src/core/database/defaultConnection.ts
729
- function defaultConnectionState() {
730
- const globalRecord = globalThis;
731
- const existing = globalRecord[DEFAULT_CONNECTION_KEY];
732
- if (existing) {
733
- return existing;
734
- }
735
- const created = { pool: null, query: null };
736
- globalRecord[DEFAULT_CONNECTION_KEY] = created;
737
- return created;
738
- }
739
- function getDefaultDatabasePool3() {
740
- const pool = defaultConnectionState().pool;
741
- if (!pool) {
742
- throw new Error("Default database pool is not registered. Call registerDefaultDatabasePool() during app bootstrap.");
743
- }
744
- return pool;
745
- }
746
- function getDefaultDatabaseQuery() {
747
- const query = defaultConnectionState().query;
748
- if (!query) {
749
- throw new Error("Default database query handle is not registered. Call registerDefaultDatabasePool() during app bootstrap.");
750
- }
751
- return query;
752
- }
753
- var DEFAULT_CONNECTION_KEY;
754
- var init_defaultConnection = __esm(() => {
755
- init_queryProxy();
756
- DEFAULT_CONNECTION_KEY = Symbol.for("@getstrata/defaultDatabaseConnection");
757
- });
758
-
759
- // ../../src/core/database/repositoryConnection.ts
760
- function resolveRepositoryConnection() {
761
- return getActiveDatabaseConnection(getBoundDatabaseConnection() ?? getDefaultDatabaseQuery());
762
- }
763
- function compileTaggedSql(strings, values) {
764
- const dialect = currentSqlDialect();
765
- let query = strings[0] ?? "";
766
- const params = [];
767
- for (let index = 0;index < values.length; index += 1) {
768
- params.push(values[index]);
769
- query += `${dialect.placeholder(params.length)}${strings[index + 1] ?? ""}`;
770
- }
771
- return { query, params };
772
- }
773
- function isTaggedStrings(value) {
774
- if (!Array.isArray(value) || typeof value[0] !== "string") {
775
- return false;
776
- }
777
- return typeof value.raw !== "undefined";
778
- }
779
- function runOnConnection(connection, args) {
780
- if (typeof connection === "function") {
781
- return connection(...args);
782
- }
783
- if (typeof connection.unsafe !== "function") {
784
- throw new Error("Database connection cannot run SQL.");
785
- }
786
- const strings = args[0];
787
- if (!isTaggedStrings(strings)) {
788
- throw new Error("Database connection cannot run tagged SQL.");
789
- }
790
- const compiled = compileTaggedSql(strings, args.slice(1));
791
- return connection.unsafe(compiled.query, compiled.params);
792
- }
793
- var repositoryConnection;
794
- var init_repositoryConnection = __esm(() => {
795
- init_boundConnection();
796
- init_connectionContext();
797
- init_defaultConnection();
798
- init_dialect();
799
- repositoryConnection = new Proxy(function repositoryConnection() {}, {
800
- apply(_target, _thisArg, args) {
801
- return runOnConnection(resolveRepositoryConnection(), args);
802
- },
803
- get(_target, property) {
804
- const connection = resolveRepositoryConnection();
805
- const value = connection[property];
806
- return typeof value === "function" ? value.bind(connection) : value;
807
- }
808
- });
809
- });
810
-
811
- // ../../src/core/database/transaction.ts
812
- import { AsyncLocalStorage as AsyncLocalStorage4 } from "async_hooks";
813
- function scopedConnection(source) {
814
- const connection = createDatabaseConnection(source);
815
- transactionAliases.set(connection, source);
816
- return connection;
817
- }
818
- function isActiveTransactionConnection(connection) {
819
- if (!hasActiveTransaction() || !hasActiveDatabaseConnection())
820
- return false;
821
- const active = getActiveDatabaseConnection(connection);
822
- return connection === active || transactionAliases.get(connection) === active;
823
- }
824
- async function runInSavepoint(connection, operation) {
825
- const inherited = transactionFrame.getStore();
826
- let parent = inherited?.connection === connection ? inherited : outerFrames.get(connection);
827
- if (!parent) {
828
- parent = { connection, childActive: false };
829
- outerFrames.set(connection, parent);
830
- }
831
- if (parent.childActive) {
832
- throw new Error("Concurrent nested transactions on one connection are not supported. Await each transaction before starting the next.");
833
- }
834
- parent.childActive = true;
835
- const name = `strata_${crypto.randomUUID().replaceAll("-", "")}`;
836
- try {
837
- return await settleTransaction(() => runWithDeferredModelEvents(async () => {
838
- await connection.unsafe(`SAVEPOINT ${name}`);
839
- try {
840
- const result = await transactionFrame.run({ connection, childActive: false }, () => runWithTransactionScope(async () => commitOrRollbackScope(await operation(scopedConnection(connection)))));
841
- await connection.unsafe(`RELEASE SAVEPOINT ${name}`);
842
- return result;
843
- } catch (error) {
844
- await connection.unsafe(`ROLLBACK TO SAVEPOINT ${name}`);
845
- await connection.unsafe(`RELEASE SAVEPOINT ${name}`);
846
- throw error;
847
- }
848
- }));
849
- } finally {
850
- parent.childActive = false;
851
- }
852
- }
853
- function supportsTransactions(connection) {
854
- return typeof connection.begin === "function";
855
- }
856
- async function runInTransaction(operation, options = {}) {
857
- const signal = options.acquisitionSignal;
858
- signal?.throwIfAborted();
859
- const admittedOperation = (connection) => {
860
- signal?.throwIfAborted();
861
- return operation(connection);
862
- };
863
- const pool = options.connection ?? resolveRepositoryConnection();
864
- if (hasActiveDatabaseConnection()) {
865
- const active = getActiveDatabaseConnection(pool);
866
- if (options.connection && options.connection !== active && options.connection !== transactionRoots.get(active) && transactionAliases.get(options.connection) !== active)
867
- throw new Error("Cannot switch database connections within an active transaction.");
868
- return await runInSavepoint(active, admittedOperation);
869
- }
870
- if (!supportsTransactions(pool)) {
871
- throw new Error("Active database connection does not support transactions. Bind a client with begin() via bindDatabaseConnection.");
872
- }
873
- return await settleTransaction(() => runWithDeferredModelEvents(async () => {
874
- let reserved;
875
- if (signal || options.acquisitionMetrics) {
876
- if (!pool.reserve)
877
- throw new Error(signal ? "Active database connection does not support cancellable transaction acquisition." : "Active database connection does not support observable transaction acquisition.");
878
- const reserve = pool.reserve.bind(pool);
879
- reserved = options.acquisitionMetrics ? await observeTransactionAcquisition(options.acquisitionMetrics, () => reserve({ signal }), signal) : await reserve({ signal });
880
- }
881
- const connection = reserved ?? pool;
882
- try {
883
- signal?.throwIfAborted();
884
- if (!supportsTransactions(connection))
885
- throw new Error("Reserved database connection does not support transactions.");
886
- return await connection.begin(AsyncLocalStorage4.bind(async (transaction) => {
887
- transactionRoots.set(transaction, pool);
888
- return await runWithDatabaseConnection(transaction, () => transactionFrame.run({ connection: transaction, childActive: false }, () => runWithTransactionScope(async () => commitOrRollbackScope(await admittedOperation(scopedConnection(transaction))))));
889
- }));
890
- } finally {
891
- await reserved?.release();
892
- }
893
- }));
894
- }
895
- var transactionFrame, outerFrames, transactionRoots, transactionAliases;
896
- var init_transaction = __esm(() => {
897
- init_deferredModelEvents();
898
- init_asyncContextStore();
899
- init_acquisitionMetrics();
900
- init_connection();
901
- init_connectionContext();
902
- init_repositoryConnection();
903
- init_transactionControl();
904
- init_acquisitionMetrics();
905
- transactionFrame = createAsyncContextStore("@getstrata/transactionFrame");
906
- outerFrames = new WeakMap;
907
- transactionRoots = new WeakMap;
908
- transactionAliases = new WeakMap;
909
- });
910
-
911
2
  // ../../src/core/runtime/optionalPeer.ts
912
3
  function missingOptionalPeer(packageName, reason, error) {
913
4
  return new Error(`Install ${packageName} ${reason} (\`bun add ${packageName}\`).`, {
@@ -927,129 +18,7 @@ function timingSafeCompareString(left, right) {
927
18
  }
928
19
 
929
20
  // ../../src/core/auth/saml/samlAssertionReplay.ts
930
- init_dialect();
931
-
932
- // ../../src/core/database/errors.ts
933
- import {
934
- BadRequestError,
935
- ConflictError,
936
- InternalServerError,
937
- toHttpError,
938
- UnprocessableEntityError
939
- } from "@getstrata/core/errors/http";
940
- function isPostgresError(error) {
941
- return typeof error === "object" && error !== null && (("errno" in error) || ("code" in error));
942
- }
943
- function getPostgresSqlState(error) {
944
- if (typeof error.errno === "string" && /^\d{5}$/.test(error.errno)) {
945
- return error.errno;
946
- }
947
- if (typeof error.errno === "number") {
948
- return String(error.errno).padStart(5, "0");
949
- }
950
- if (typeof error.code === "string" && /^\d{5}$/.test(error.code)) {
951
- return error.code;
952
- }
953
- return;
954
- }
955
- var MYSQL_ERRNO_MESSAGES = {
956
- 1062: () => new ConflictError("A record with these values already exists."),
957
- 1451: () => new UnprocessableEntityError("Record is still referenced by other records."),
958
- 1452: () => new UnprocessableEntityError("Referenced record does not exist."),
959
- 1048: () => new BadRequestError("Required field is missing."),
960
- 3819: () => new BadRequestError("Value violates a database constraint.")
961
- };
962
- function mapSqliteError(error) {
963
- const code = typeof error.code === "string" ? error.code : "";
964
- if (!code.startsWith("SQLITE_")) {
965
- return null;
966
- }
967
- if (code === "SQLITE_CONSTRAINT_UNIQUE" || code === "SQLITE_CONSTRAINT_PRIMARYKEY") {
968
- return new ConflictError("A record with these values already exists.");
969
- }
970
- if (code === "SQLITE_CONSTRAINT_FOREIGNKEY") {
971
- return new UnprocessableEntityError("Operation conflicts with related records.");
972
- }
973
- if (code === "SQLITE_CONSTRAINT_NOTNULL") {
974
- return new BadRequestError("Required field is missing.");
975
- }
976
- if (code.startsWith("SQLITE_CONSTRAINT")) {
977
- return new BadRequestError("Value violates a database constraint.");
978
- }
979
- return new InternalServerError("Database operation failed.");
980
- }
981
- function mapMysqlError(error) {
982
- const code = typeof error.code === "string" ? error.code : "";
983
- if (!code.startsWith("ER_")) {
984
- return null;
985
- }
986
- const factory = typeof error.errno === "number" ? MYSQL_ERRNO_MESSAGES[error.errno] : undefined;
987
- return factory ? factory() : new InternalServerError("Database operation failed.");
988
- }
989
- function mapDatabaseError(error) {
990
- const httpError = toHttpError(error);
991
- if (httpError) {
992
- return httpError;
993
- }
994
- if (!isPostgresError(error)) {
995
- return new InternalServerError;
996
- }
997
- const sqlite = mapSqliteError(error);
998
- if (sqlite) {
999
- return sqlite;
1000
- }
1001
- const mysql = mapMysqlError(error);
1002
- if (mysql) {
1003
- return mysql;
1004
- }
1005
- const sqlState = getPostgresSqlState(error);
1006
- switch (sqlState) {
1007
- case "23505":
1008
- if (error.detail) {
1009
- console.error("[database] unique violation", error.detail);
1010
- }
1011
- return new ConflictError("A record with these values already exists.");
1012
- case "23503":
1013
- if (error.detail) {
1014
- console.error("[database] foreign-key violation", error.detail);
1015
- }
1016
- return new UnprocessableEntityError("Operation conflicts with related records.");
1017
- case "23502":
1018
- if (error.detail) {
1019
- console.error("[database] not-null violation", error.detail);
1020
- }
1021
- return new BadRequestError("Required field is missing.");
1022
- case "23514":
1023
- if (error.detail) {
1024
- console.error("[database] check violation", error.detail);
1025
- }
1026
- return new BadRequestError("Value violates a database constraint.");
1027
- default:
1028
- return new InternalServerError("Database operation failed.");
1029
- }
1030
- }
1031
- async function withDatabaseErrorHandling(operation) {
1032
- try {
1033
- return await operation();
1034
- } catch (error) {
1035
- throw mapDatabaseError(error);
1036
- }
1037
- }
1038
- function isUniqueConstraintError(error) {
1039
- if (!isPostgresError(error)) {
1040
- return false;
1041
- }
1042
- if (error.code === "SQLITE_CONSTRAINT_UNIQUE" || error.code === "SQLITE_CONSTRAINT_PRIMARYKEY") {
1043
- return true;
1044
- }
1045
- if (error.errno === 1062) {
1046
- return true;
1047
- }
1048
- return getPostgresSqlState(error) === "23505";
1049
- }
1050
-
1051
- // ../../src/core/auth/saml/samlAssertionReplay.ts
1052
- init_transaction();
21
+ import { isUniqueConstraintError } from "@getstrata/core/database/errors";
1053
22
  var REPLAY_RETENTION_MS = 60 * 60 * 1000;
1054
23
 
1055
24
  class InMemorySamlAssertionReplayStore {
@@ -1074,40 +43,28 @@ class InMemorySamlAssertionReplayStore {
1074
43
  }
1075
44
  }
1076
45
  }
1077
-
1078
- class SqlSamlAssertionReplayStore {
1079
- async consume(assertionId) {
1080
- const dialect = currentSqlDialect();
1081
- try {
1082
- await runInTransaction(async (connection) => {
1083
- await connection.unsafe(`INSERT INTO auth_saml_assertions (assertion_id, consumed_at) VALUES (${dialect.placeholder(1)}, ${dialect.placeholder(2)})`, [assertionId, dialect.timestampValue(new Date)]);
1084
- await connection.unsafe(`DELETE FROM auth_saml_assertions WHERE consumed_at < ${dialect.placeholder(1)}`, [dialect.timestampValue(new Date(Date.now() - REPLAY_RETENTION_MS))]);
46
+ async function consumeSqlAssertion(run, assertionId) {
47
+ try {
48
+ await run(async ({ dialect, execute }) => {
49
+ await execute({
50
+ text: `INSERT INTO auth_saml_assertions (assertion_id, consumed_at) VALUES (${dialect.placeholder(1)}, ${dialect.placeholder(2)})`,
51
+ params: [assertionId, dialect.timestampValue(new Date)]
1085
52
  });
1086
- } catch (error) {
1087
- if (isUniqueConstraintError(error)) {
1088
- throw new Error("SAML assertion replay detected.");
1089
- }
1090
- throw error;
1091
- }
1092
- }
1093
- }
1094
- var sqlReplayStore = new SqlSamlAssertionReplayStore;
1095
- var replayStoreOverride = null;
1096
- function samlAssertionReplayStore() {
1097
- return replayStoreOverride ?? sqlReplayStore;
1098
- }
1099
- function setSamlAssertionReplayStoreForTests(store) {
1100
- replayStoreOverride = store;
1101
- }
1102
- function resetSamlReplayCacheForTests() {
1103
- if (replayStoreOverride instanceof InMemorySamlAssertionReplayStore) {
1104
- replayStoreOverride.clear();
1105
- return;
53
+ await execute({
54
+ text: `DELETE FROM auth_saml_assertions WHERE consumed_at < ${dialect.placeholder(1)}`,
55
+ params: [dialect.timestampValue(new Date(Date.now() - REPLAY_RETENTION_MS))]
56
+ });
57
+ });
58
+ } catch (error) {
59
+ if (isUniqueConstraintError(error))
60
+ throw new Error("SAML assertion replay detected.");
61
+ throw error;
1106
62
  }
1107
- replayStoreOverride = null;
1108
63
  }
1109
- async function consumeSamlAssertion(assertionId) {
1110
- await samlAssertionReplayStore().consume(assertionId);
64
+ function createSqlSamlAssertionReplayStore(selected) {
65
+ return Object.freeze({
66
+ consume: (assertionId) => consumeSqlAssertion((work) => selected.transaction((child) => work({ dialect: child.dialect, execute: (statement) => child.execute(statement) })), assertionId)
67
+ });
1111
68
  }
1112
69
 
1113
70
  // ../../src/core/auth/saml/samlServiceProvider.ts
@@ -1164,12 +121,12 @@ function requireSamlOption(value, name) {
1164
121
  }
1165
122
  return trimmed;
1166
123
  }
1167
- function readSamlEnvOptions() {
1168
- const idpSsoUrl = process.env.SAML_IDP_SSO_URL?.trim() ?? "";
1169
- const idpCert = process.env.SAML_IDP_CERT?.trim() ?? "";
1170
- const spEntityId = process.env.SAML_SP_ENTITY_ID?.trim() ?? "";
1171
- const acsUrl = process.env.SAML_ACS_URL?.trim() ?? "";
1172
- const idpIssuer = process.env.SAML_IDP_ISSUER?.trim() ?? "";
124
+ function readSamlEnvOptions(env = process.env) {
125
+ const idpSsoUrl = env.SAML_IDP_SSO_URL?.trim() ?? "";
126
+ const idpCert = env.SAML_IDP_CERT?.trim() ?? "";
127
+ const spEntityId = env.SAML_SP_ENTITY_ID?.trim() ?? "";
128
+ const acsUrl = env.SAML_ACS_URL?.trim() ?? "";
129
+ const idpIssuer = env.SAML_IDP_ISSUER?.trim() ?? "";
1173
130
  if (!idpSsoUrl || !idpCert || !spEntityId || !acsUrl || !idpIssuer) {
1174
131
  throw new Error("SAML requires SAML_IDP_SSO_URL, SAML_IDP_CERT, SAML_SP_ENTITY_ID, SAML_ACS_URL, and SAML_IDP_ISSUER.");
1175
132
  }
@@ -1179,8 +136,8 @@ function readSamlEnvOptions() {
1179
136
  spEntityId,
1180
137
  acsUrl,
1181
138
  idpIssuer,
1182
- wantAuthnResponseSigned: process.env.SAML_WANT_RESPONSE_SIGNED !== "false",
1183
- disableRequestedAuthnContext: process.env.SAML_DISABLE_REQUESTED_AUTHN_CONTEXT === "true"
139
+ wantAuthnResponseSigned: env.SAML_WANT_RESPONSE_SIGNED !== "false",
140
+ disableRequestedAuthnContext: env.SAML_DISABLE_REQUESTED_AUTHN_CONTEXT === "true"
1184
141
  };
1185
142
  }
1186
143
  var nodeSamlLoader = null;
@@ -1199,15 +156,31 @@ function setNodeSamlLoaderForTests(loader) {
1199
156
  }
1200
157
 
1201
158
  class SamlServiceProvider {
1202
- options;
1203
159
  client = null;
160
+ options;
161
+ consumeAssertion;
1204
162
  constructor(options) {
1205
- this.options = options;
1206
- requireSamlOption(options.idpSsoUrl, "idpSsoUrl");
1207
- requireSamlOption(options.idpCert, "idpCert");
1208
- requireSamlOption(options.spEntityId, "spEntityId");
1209
- requireSamlOption(options.acsUrl, "acsUrl");
1210
- requireSamlOption(options.idpIssuer, "idpIssuer");
163
+ const store = options?.replayStore;
164
+ const consume = store?.consume;
165
+ if (typeof consume !== "function")
166
+ throw new TypeError("SAML requires an explicit replayStore with consume().");
167
+ this.consumeAssertion = consume.bind(store);
168
+ const config = {
169
+ idpSsoUrl: options.idpSsoUrl,
170
+ idpCert: options.idpCert,
171
+ spEntityId: options.spEntityId,
172
+ acsUrl: options.acsUrl,
173
+ idpIssuer: options.idpIssuer,
174
+ wantAssertionsSigned: options.wantAssertionsSigned,
175
+ wantAuthnResponseSigned: options.wantAuthnResponseSigned,
176
+ disableRequestedAuthnContext: options.disableRequestedAuthnContext
177
+ };
178
+ requireSamlOption(config.idpSsoUrl, "idpSsoUrl");
179
+ requireSamlOption(config.idpCert, "idpCert");
180
+ requireSamlOption(config.spEntityId, "spEntityId");
181
+ requireSamlOption(config.acsUrl, "acsUrl");
182
+ requireSamlOption(config.idpIssuer, "idpIssuer");
183
+ this.options = Object.freeze(config);
1211
184
  }
1212
185
  async getClient() {
1213
186
  if (this.client) {
@@ -1254,7 +227,7 @@ class SamlServiceProvider {
1254
227
  }
1255
228
  assertBearerRecipient(profile, this.options.acsUrl);
1256
229
  await assertResponseDestination(profile, this.options.acsUrl);
1257
- await consumeSamlAssertion(assertionId);
230
+ await this.consumeAssertion(assertionId);
1258
231
  const email = profile.email || (typeof profile["urn:oid:0.9.2342.19200300.100.1.3"] === "string" ? profile["urn:oid:0.9.2342.19200300.100.1.3"] : "") || "";
1259
232
  if (!email) {
1260
233
  throw new Error("SAML assertion did not include an email address.");
@@ -1266,7 +239,7 @@ class SamlServiceProvider {
1266
239
  };
1267
240
  }
1268
241
  }
1269
- function createSamlServiceProvider(options = readSamlEnvOptions()) {
242
+ function createSamlServiceProvider(options) {
1270
243
  return new SamlServiceProvider(options);
1271
244
  }
1272
245