@getstrata/bootstrap 2.2.60 → 3.0.4

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 (90) hide show
  1. package/CHANGELOG.md +24 -0
  2. package/dist/bootstrap/app.d.ts +18 -7
  3. package/dist/bootstrap/buildModuleRoutes.d.ts +3 -5
  4. package/dist/bootstrap/buildWebModuleRoutes.d.ts +2 -3
  5. package/dist/bootstrap/cache/modelCacheTags.d.ts +3 -2
  6. package/dist/bootstrap/cachedJson.d.ts +7 -2
  7. package/dist/bootstrap/config.d.ts +1 -1
  8. package/dist/bootstrap/context.d.ts +25 -7
  9. package/dist/bootstrap/contracts.d.ts +1 -0
  10. package/dist/bootstrap/createWebRoutes.d.ts +2 -1
  11. package/dist/bootstrap/databaseReadiness.d.ts +3 -0
  12. package/dist/bootstrap/dependencies.d.ts +3 -2
  13. package/dist/bootstrap/discoverJobs.d.ts +3 -2
  14. package/dist/bootstrap/discoverListeners.d.ts +10 -7
  15. package/dist/bootstrap/discoverModels.d.ts +3 -2
  16. package/dist/bootstrap/discoverModules.d.ts +7 -6
  17. package/dist/bootstrap/health.d.ts +3 -2
  18. package/dist/bootstrap/http/securedRouteModelBinding.d.ts +1 -1
  19. package/dist/bootstrap/httpKernel.d.ts +43 -22
  20. package/dist/bootstrap/httpPersistence.d.ts +4 -0
  21. package/dist/bootstrap/inProcessCron.d.ts +5 -5
  22. package/dist/bootstrap/listeners/invalidateCacheOnModelWrite.d.ts +13 -12
  23. package/dist/bootstrap/metricsRoutes.d.ts +6 -1
  24. package/dist/bootstrap/moduleRouteMiddleware.d.ts +4 -4
  25. package/dist/bootstrap/modules.d.ts +1 -1
  26. package/dist/bootstrap/ownedHttpRoute.d.ts +23 -0
  27. package/dist/bootstrap/persistenceContracts.d.ts +70 -0
  28. package/dist/bootstrap/persistenceInvocation.d.ts +4 -0
  29. package/dist/bootstrap/providers/auth.d.ts +21 -0
  30. package/dist/bootstrap/providers/cache.d.ts +9 -3
  31. package/dist/bootstrap/providers/cacheProvider.d.ts +3 -0
  32. package/dist/bootstrap/providers/config.d.ts +6 -3
  33. package/dist/bootstrap/providers/events.d.ts +5 -2
  34. package/dist/bootstrap/providers/index.d.ts +3 -2
  35. package/dist/bootstrap/providers/listeners.d.ts +3 -3
  36. package/dist/bootstrap/providers/mail.d.ts +15 -0
  37. package/dist/bootstrap/providers/queue.d.ts +3 -2
  38. package/dist/bootstrap/providers/storage.d.ts +11 -2
  39. package/dist/bootstrap/providers/tracing.d.ts +4 -2
  40. package/dist/bootstrap/providers/view.d.ts +8 -5
  41. package/dist/bootstrap/public-api.d.ts +10 -7
  42. package/dist/bootstrap/queue/defaultJobs.d.ts +4 -2
  43. package/dist/bootstrap/rateLimit.d.ts +13 -3
  44. package/dist/bootstrap/routeCompiler.d.ts +20 -0
  45. package/dist/bootstrap/routeMetadata.d.ts +3 -3
  46. package/dist/bootstrap/routePlan.d.ts +11 -0
  47. package/dist/bootstrap/schedule.d.ts +11 -2
  48. package/dist/bootstrap/secretsGuard.d.ts +2 -3
  49. package/dist/bootstrap/web/routing.d.ts +6 -3
  50. package/dist/bootstrap/web/server.d.ts +14 -4
  51. package/dist/bootstrap/web/session.d.ts +23 -16
  52. package/dist/entries/buildModuleRoutes.js +602 -384
  53. package/dist/entries/buildWebModuleRoutes.js +596 -347
  54. package/dist/entries/cache/modelCacheTags.js +8 -186
  55. package/dist/entries/cachedJson.js +22 -0
  56. package/dist/entries/config.js +1 -3
  57. package/dist/entries/context.js +665 -700
  58. package/dist/entries/createSpaRoutes.js +194 -5
  59. package/dist/entries/createWebRoutes.js +618 -367
  60. package/dist/entries/databaseReadiness.js +267 -0
  61. package/dist/entries/dependencies.js +666 -701
  62. package/dist/entries/discoverJobs.js +18 -16
  63. package/dist/entries/discoverListeners.js +27 -38
  64. package/dist/entries/discoverModels.js +4 -3
  65. package/dist/entries/discoverModules.js +29 -67
  66. package/dist/entries/health.js +14 -34
  67. package/dist/entries/httpKernel.js +405 -89
  68. package/dist/entries/listeners/invalidateCacheOnModelWrite.js +43 -289
  69. package/dist/entries/metricsRoutes.js +9 -5
  70. package/dist/entries/persistenceContracts.js +1 -0
  71. package/dist/entries/persistenceInvocation.js +17 -0
  72. package/dist/entries/providers/auth.js +114 -0
  73. package/dist/entries/providers/cache.js +35 -0
  74. package/dist/entries/providers/events.js +55 -0
  75. package/dist/entries/providers/view.js +34 -44
  76. package/dist/entries/providers.js +392 -561
  77. package/dist/entries/queue/defaultJobs.js +9 -6
  78. package/dist/entries/routePlan.js +200 -0
  79. package/dist/entries/schedule.js +37 -37
  80. package/dist/entries/secretsGuard.js +10 -13
  81. package/dist/entries/web/routing.js +412 -96
  82. package/dist/entries/web/server.js +461 -29
  83. package/dist/entries/web/session.js +61 -73
  84. package/dist/index.js +1520 -1085
  85. package/dist/internal/ownedHttpRoute.js +66 -0
  86. package/package.json +52 -15
  87. package/dist/bootstrap/applicationRegistry.d.ts +0 -1
  88. package/dist/bootstrap/routeRegistry.d.ts +0 -10
  89. package/dist/entries/applicationRegistry.js +0 -24
  90. package/dist/entries/routeRegistry.js +0 -29
package/dist/index.js CHANGED
@@ -8,38 +8,38 @@ import {
8
8
  SchedulerLeaseLostError
9
9
  } from "@getstrata/core/scheduler/schedule";
10
10
 
11
- // ../../src/bootstrap/applicationRegistry.ts
12
- import {
13
- resolveApplicationAuth,
14
- resolveApplicationCache,
15
- resolveApplicationConfig,
16
- resolveApplicationDependencies,
17
- resolveApplicationEventBus,
18
- resolveApplicationLogger,
19
- resolveApplicationPolicyGate,
20
- resolveApplicationQueue,
21
- setActiveApplicationContext
22
- } from "@getstrata/core/runtime/applicationRegistry";
11
+ // ../../src/bootstrap/buildModuleRoutes.ts
12
+ import { withMiddleware as withMiddleware2 } from "@getstrata/core/http/routeMiddleware";
13
+ import { identityModes as identityModes2, scimMiddleware as scimMiddleware2 } from "#strata-http-route";
14
+
23
15
  // ../../src/bootstrap/cachedJson.ts
24
- import { conditionalJsonResponse } from "@getstrata/core/http/conditionalResponse";
25
- function createCachedJson(dependencies) {
16
+ import { CORE_JSON_RESPONSE_POLICY_TOKEN } from "@getstrata/core/contracts/serviceTokens";
17
+ import {
18
+ conditionalJsonResponse,
19
+ snapshotJsonResponsePolicy
20
+ } from "@getstrata/core/http/conditionalResponse";
21
+ function createCachedJson(cache, policy) {
22
+ const responsePolicy = snapshotJsonResponsePolicy(policy);
26
23
  return async (cacheKey, loader, tags = [], request) => {
27
- const data = tags.length > 0 ? await dependencies.cache.tags(...tags).remember(cacheKey, loader) : await dependencies.cache.remember(cacheKey, loader);
28
- return conditionalJsonResponse(request, data);
24
+ const data = tags.length > 0 ? await cache.tags(...tags).remember(cacheKey, loader) : await cache.remember(cacheKey, loader);
25
+ return conditionalJsonResponse(request, data, responsePolicy);
29
26
  };
30
27
  }
28
+ function createApplicationCachedJson(dependencies) {
29
+ const policy = dependencies.container.has(CORE_JSON_RESPONSE_POLICY_TOKEN) ? dependencies.container.resolve(CORE_JSON_RESPONSE_POLICY_TOKEN) : { etagEnabled: true };
30
+ return createCachedJson(dependencies.cache, policy);
31
+ }
31
32
 
32
33
  // ../../src/bootstrap/httpKernel.ts
34
+ import { establishedAuthReader as establishedAuthReader2 } from "@getstrata/core/auth/authReader";
35
+ import { hasVerifiedEmail } from "@getstrata/core/auth/emailVerification";
33
36
  import {
34
- hasVerifiedEmail,
35
- isEmailVerificationRequired
36
- } from "@getstrata/core/auth/emailVerification";
37
- import { createMembershipMiddleware } from "@getstrata/core/auth/membershipMiddleware";
38
- import { resolveAbilityChecker } from "@getstrata/core/contracts/serviceTokens";
39
- import { createAuthMiddleware } from "@getstrata/core/http/authMiddleware";
37
+ CORE_TRACING_RUNTIME_TOKEN,
38
+ resolveAbilityChecker
39
+ } from "@getstrata/core/contracts/serviceTokens";
40
40
  import { createAuthorizeMiddleware } from "@getstrata/core/http/authorizeMiddleware";
41
41
  import { createBodySizeLimitMiddleware } from "@getstrata/core/http/bodySizeLimitMiddleware";
42
- import { createCorsMiddleware } from "@getstrata/core/http/corsMiddleware";
42
+ import { createCorsMiddleware, resolveCorsConfig } from "@getstrata/core/http/corsMiddleware";
43
43
  import { createCsrfMiddleware } from "@getstrata/core/http/csrfMiddleware";
44
44
  import { createFlashMiddleware } from "@getstrata/core/http/flashMiddleware";
45
45
  import { createLoginThrottleMiddleware } from "@getstrata/core/http/loginThrottleMiddleware";
@@ -52,21 +52,21 @@ import { createRequireGlobalAdminMiddleware } from "@getstrata/core/http/require
52
52
  import { createRequirePasswordConfirmMiddleware } from "@getstrata/core/http/requirePasswordConfirmMiddleware";
53
53
  import { createRequireVerifiedMiddleware } from "@getstrata/core/http/requireVerifiedMiddleware";
54
54
  import { createRequireWebAuthMiddleware } from "@getstrata/core/http/requireWebAuthMiddleware";
55
- import {
56
- createJsonErrorMiddleware,
57
- createWebErrorMiddleware,
58
- withErrorHandling,
59
- withJsonErrorHandling
60
- } from "@getstrata/core/http/response";
55
+ import { createJsonErrorMiddleware, createWebErrorMiddleware } from "@getstrata/core/http/response";
61
56
  import { withMiddleware } from "@getstrata/core/http/routeMiddleware";
62
57
  import { createSecurityHeadersMiddleware } from "@getstrata/core/http/securityHeadersMiddleware";
63
58
  import { createValidateSignatureMiddleware } from "@getstrata/core/http/signedUrl";
64
59
  import { createThrottleMiddleware } from "@getstrata/core/http/throttleMiddleware";
65
60
  import { createRequestLoggingMiddleware } from "@getstrata/core/logging/requestLoggingMiddleware";
66
- import { isViewsEnabled } from "@getstrata/core/runtime/frontendMode";
67
- import { isPublicReadsEnabled } from "@getstrata/core/security/publicReads";
68
- import { createTenantMiddleware } from "@getstrata/core/tenant/tenantMiddleware";
69
61
  import { createTracingMiddleware } from "@getstrata/core/tracing/tracingMiddleware";
62
+ import { CORE_WEB_ERROR_VIEW_TOKEN } from "@getstrata/core/view/tokens";
63
+ import {
64
+ assertHttpHandler,
65
+ identityModes,
66
+ ownedHttpRoute,
67
+ ownedPublicHttpRoute,
68
+ scimMiddleware
69
+ } from "#strata-http-route";
70
70
 
71
71
  // ../../src/bootstrap/config.ts
72
72
  import {
@@ -81,8 +81,7 @@ import {
81
81
  CORE_PUBLIC_TENANCY_TOKEN,
82
82
  CORE_QUEUE_TOKEN,
83
83
  CORE_TENANT_RESOLVER_TOKEN,
84
- CORE_THROTTLE_QUOTA_POLICY_TOKEN,
85
- CORE_TOKEN_SERVICE_TOKEN
84
+ CORE_THROTTLE_QUOTA_POLICY_TOKEN
86
85
  } from "@getstrata/core/contracts/serviceTokens";
87
86
  var APP_PORT_CONFIG_KEY = "app.port";
88
87
  var CACHE_TTL_MS_CONFIG_KEY = "cache.ttlMs";
@@ -98,6 +97,189 @@ var DEFAULT_CACHE_DRIVER = "array";
98
97
  var DEFAULT_API_TOKEN = "";
99
98
  var DEFAULT_QUEUE_DRIVER = "sync";
100
99
 
100
+ // ../../src/bootstrap/httpPersistence.ts
101
+ import { establishedAuthReader, runWithEstablishedAuth } from "@getstrata/core/auth/authReader";
102
+ import { validatedAuthOutcome } from "@getstrata/core/auth/guard";
103
+ import { runWithMembershipSnapshot } from "@getstrata/core/auth/membershipContext";
104
+ import { InternalServerError, InvalidCredentialsError } from "@getstrata/core/errors/http";
105
+ import { currentRequestMeta } from "@getstrata/core/http/requestMetaContext";
106
+ import { errorResponse } from "@getstrata/core/http/response";
107
+ import { webErrorResponse } from "@getstrata/core/http/webErrorResponse";
108
+ import { createPublicTenantSelector } from "@getstrata/core/tenant/publicTenantHost";
109
+ import { runWithTenant } from "@getstrata/core/tenant/tenantContext";
110
+ import { DEFAULT_TENANT, resolveTenantForRequest } from "@getstrata/core/tenant/tenantMiddleware";
111
+ import { businessPorts } from "#strata-http-route";
112
+ import { HTTP_PERSISTENCE_OPTIONS } from "#strata-http-route";
113
+ function snapshotAuth(input) {
114
+ const auth = validatedAuthOutcome(input);
115
+ if (auth.status === "error")
116
+ throw Object.assign(new InternalServerError, { cause: auth.error });
117
+ if (auth.status === "invalid")
118
+ throw new InvalidCredentialsError;
119
+ const user = auth.user;
120
+ const name = user?.name;
121
+ const email = user?.email;
122
+ return Object.freeze({
123
+ credentialSource: auth.credentialSource,
124
+ user: user ? Object.freeze({
125
+ id: user.id,
126
+ ...typeof name === "string" ? { name } : {},
127
+ ...typeof email === "string" ? { email } : {},
128
+ ...user.role !== undefined ? { role: user.role } : {},
129
+ ...user.isActive !== undefined ? { isActive: user.isActive } : {},
130
+ ...user.authVersion !== undefined ? { authVersion: user.authVersion } : {},
131
+ ...user.tokenId !== undefined ? { tokenId: user.tokenId } : {},
132
+ ...user.abilities ? { abilities: Object.freeze([...user.abilities]) } : {},
133
+ ...user.emailVerifiedAt !== undefined ? {
134
+ emailVerifiedAt: user.emailVerifiedAt instanceof Date ? user.emailVerifiedAt.toISOString() : user.emailVerifiedAt
135
+ } : {}
136
+ }) : null
137
+ });
138
+ }
139
+ function snapshotTenant(tenant) {
140
+ const snapshot = structuredClone(tenant);
141
+ if (!snapshot || typeof snapshot !== "object" || Array.isArray(snapshot) || !Number.isSafeInteger(snapshot.id) || snapshot.id < 1 || typeof snapshot.slug !== "string")
142
+ throw new TypeError("HTTP metadata must establish a valid tenant identity.");
143
+ return Object.freeze(snapshot);
144
+ }
145
+ function createHttpPersistence(invoke, options) {
146
+ const invalidSessionCookie = options.invalidSessionCookie ? Object.freeze({ ...options.invalidSessionCookie }) : undefined;
147
+ const selectPublic = options.publicTenancy ? createPublicTenantSelector(options.publicTenancy) : undefined;
148
+ return async (request, handler, identity, scim = false) => {
149
+ const externalId = currentRequestMeta().requestId;
150
+ const metadata = { routeTemplate: currentRequestMeta().routeTemplate ?? "", phase: "metadata" };
151
+ const established = await invoke({
152
+ kind: "request",
153
+ externalId,
154
+ signal: request.signal,
155
+ metadata,
156
+ actor: { kind: "system", policy: "http.identity-metadata" }
157
+ }, async (ports) => {
158
+ if (scim) {
159
+ if (!options.scim)
160
+ throw new Error("Explicit SCIM metadata authentication is required.");
161
+ const tenant = await options.scim(request, ports.database);
162
+ if (tenant instanceof Response)
163
+ return tenant;
164
+ return Object.freeze({
165
+ auth: Object.freeze({ user: null, credentialSource: "bearer" }),
166
+ memberships: Object.freeze([]),
167
+ tenant: snapshotTenant(tenant)
168
+ });
169
+ }
170
+ const lookup = options.metadata(ports);
171
+ const outcome = validatedAuthOutcome(await lookup.authenticate(request));
172
+ if (outcome.status === "invalid" && outcome.credentialSource === "session" && invalidSessionCookie && request.headers.get("cookie")?.split(";").some((part) => part.trim().startsWith(`${invalidSessionCookie.name}=`))) {
173
+ const error = new InvalidCredentialsError;
174
+ const response = await webErrorResponse(error, request) ?? errorResponse(error);
175
+ response.headers.append("Set-Cookie", invalidSessionCookie.expiredHeader);
176
+ return response;
177
+ }
178
+ const auth = snapshotAuth(outcome);
179
+ const memberships = auth.user ? await lookup.memberships(auth.user) : [];
180
+ const resolveTenant = async (id) => {
181
+ const result = await lookup.tenant(id);
182
+ if (result === null)
183
+ return null;
184
+ const snapshot = snapshotTenant(result);
185
+ if (snapshot.id !== id)
186
+ throw new Error("Tenant resolver returned a different tenant identity.");
187
+ return snapshot;
188
+ };
189
+ const tenant = options.tenancy === "none" ? snapshotTenant(DEFAULT_TENANT) : await resolveTenantForRequest(request, {
190
+ auth,
191
+ config: {
192
+ enabled: true,
193
+ production: options.production,
194
+ allowDevHeaders: options.allowTenantDevHeaders
195
+ },
196
+ resolveTenant,
197
+ userTenantId: lookup.userTenantId
198
+ }, resolveTenant, selectPublic);
199
+ return Object.freeze({
200
+ auth,
201
+ tenant,
202
+ memberships: Object.freeze(memberships.map((row) => Object.freeze({ ...row })))
203
+ });
204
+ });
205
+ if (established instanceof Response)
206
+ return established;
207
+ const claims = {};
208
+ if (established.auth.user) {
209
+ for (const [key, value] of Object.entries(established.auth.user))
210
+ if (value !== undefined) {
211
+ if (value === null || typeof value === "string" || typeof value === "number" || typeof value === "boolean" || Array.isArray(value))
212
+ claims[key] = value;
213
+ }
214
+ }
215
+ return invoke({
216
+ kind: "request",
217
+ externalId,
218
+ signal: request.signal,
219
+ metadata: {
220
+ ...metadata,
221
+ phase: identity ? "identity-operation" : "business",
222
+ credentialSource: established.auth.credentialSource
223
+ },
224
+ ...scim ? { actor: { kind: "system", policy: "http.scim" } } : identity ? { actor: { kind: "system", policy: "http.identity-operation" } } : established.auth.user ? { actor: { kind: "principal", claims } } : {},
225
+ tenant: { id: established.tenant.id, slug: established.tenant.slug }
226
+ }, (ports) => {
227
+ const policy = Object.freeze({
228
+ run: (selected, mode, work) => {
229
+ const allowed = mode.kind === "tenant" ? identity === undefined : identity?.includes(mode.kind) === true;
230
+ if (!allowed)
231
+ throw new Error("Database policy is not allowed by this route declaration.");
232
+ return ports.policy.run(selected, mode, work);
233
+ }
234
+ });
235
+ const work = (database) => runWithEstablishedAuth(request, established.auth, () => runWithMembershipSnapshot(established.memberships, () => {
236
+ const execute = () => handler(request, businessPorts({
237
+ database,
238
+ auth: establishedAuthReader,
239
+ established,
240
+ policy
241
+ }));
242
+ return runWithTenant(established.tenant, execute);
243
+ }));
244
+ return !identity && options.tenancy === "rls" ? ports.policy.run(ports.database, { kind: "tenant", tenantId: established.tenant.id }, work) : work(ports.database);
245
+ });
246
+ };
247
+ }
248
+
249
+ // ../../src/bootstrap/moduleRouteMiddleware.ts
250
+ function enterModuleRoutes(routes, enter) {
251
+ const wrapped = {};
252
+ for (const [path, value] of Object.entries(routes)) {
253
+ if (value instanceof Response) {
254
+ const methods = {};
255
+ for (const method of ["GET", "HEAD", "POST", "PUT", "DELETE", "PATCH", "OPTIONS"]) {
256
+ methods[method] = enter(() => value.clone());
257
+ }
258
+ wrapped[path] = methods;
259
+ continue;
260
+ }
261
+ if (typeof value === "function") {
262
+ wrapped[path] = enter(value);
263
+ continue;
264
+ }
265
+ if (value && typeof value === "object" && !Array.isArray(value)) {
266
+ const entries = Object.entries(value);
267
+ if (entries.some(([, handler]) => typeof handler === "function" || handler instanceof Response)) {
268
+ wrapped[path] = Object.fromEntries(entries.map(([method, handler]) => {
269
+ const callback = handler instanceof Response ? () => handler.clone() : handler;
270
+ return [
271
+ method,
272
+ typeof callback === "function" ? enter(callback) : callback
273
+ ];
274
+ }));
275
+ continue;
276
+ }
277
+ }
278
+ wrapped[path] = value;
279
+ }
280
+ return wrapped;
281
+ }
282
+
101
283
  // ../../src/bootstrap/rateLimit.ts
102
284
  var LOCAL_LOGIN_RATE_LIMIT = {
103
285
  maxAttempts: 100,
@@ -107,9 +289,6 @@ var PRODUCTION_LOGIN_RATE_LIMIT = {
107
289
  maxAttempts: 5,
108
290
  decaySeconds: 900
109
291
  };
110
- function isLocalAppEnv() {
111
- return (process.env.APP_ENV ?? "local") === "local";
112
- }
113
292
  function parsePositiveInt(value, fallback) {
114
293
  const parsed = Number(value);
115
294
  if (!Number.isFinite(parsed) || parsed <= 0) {
@@ -129,18 +308,18 @@ function parseWindowSeconds(secondsValue, msValue, fallback) {
129
308
  }
130
309
  return fallback;
131
310
  }
132
- function resolveLoginRateLimit() {
133
- const defaults = isLocalAppEnv() ? LOCAL_LOGIN_RATE_LIMIT : PRODUCTION_LOGIN_RATE_LIMIT;
311
+ function resolveLoginRateLimit(env = {}) {
312
+ const defaults = env.APP_ENV === "local" ? LOCAL_LOGIN_RATE_LIMIT : PRODUCTION_LOGIN_RATE_LIMIT;
134
313
  return {
135
- maxAttempts: parsePositiveInt(process.env.LOGIN_RATE_LIMIT_PER_WINDOW, defaults.maxAttempts),
136
- decaySeconds: parseWindowSeconds(process.env.LOGIN_RATE_LIMIT_WINDOW_SECONDS, process.env.LOGIN_RATE_LIMIT_WINDOW_MS, defaults.decaySeconds)
314
+ maxAttempts: parsePositiveInt(env.LOGIN_RATE_LIMIT_PER_WINDOW, defaults.maxAttempts),
315
+ decaySeconds: parseWindowSeconds(env.LOGIN_RATE_LIMIT_WINDOW_SECONDS, env.LOGIN_RATE_LIMIT_WINDOW_MS, defaults.decaySeconds)
137
316
  };
138
317
  }
139
- function resolveRegisterRateLimit() {
140
- const defaults = isLocalAppEnv() ? { maxAttempts: 100, decaySeconds: 60 } : { maxAttempts: 10, decaySeconds: 60 };
318
+ function resolveRegisterRateLimit(env = {}) {
319
+ const defaults = env.APP_ENV === "local" ? { maxAttempts: 100, decaySeconds: 60 } : { maxAttempts: 10, decaySeconds: 60 };
141
320
  return {
142
- maxAttempts: parsePositiveInt(process.env.REGISTER_RATE_LIMIT_PER_WINDOW, defaults.maxAttempts),
143
- decaySeconds: parseWindowSeconds(process.env.REGISTER_RATE_LIMIT_WINDOW_SECONDS, process.env.REGISTER_RATE_LIMIT_WINDOW_MS, defaults.decaySeconds)
321
+ maxAttempts: parsePositiveInt(env.REGISTER_RATE_LIMIT_PER_WINDOW, defaults.maxAttempts),
322
+ decaySeconds: parseWindowSeconds(env.REGISTER_RATE_LIMIT_WINDOW_SECONDS, env.REGISTER_RATE_LIMIT_WINDOW_MS, defaults.decaySeconds)
144
323
  };
145
324
  }
146
325
 
@@ -149,15 +328,78 @@ class HttpKernel {
149
328
  dependencies;
150
329
  ownedThrottles = new Set;
151
330
  disposed = false;
331
+ emailVerificationRequired;
332
+ viewsEnabled;
333
+ publicReadsEnabled;
334
+ etagEnabled;
335
+ httpOptions;
336
+ responsePolicy;
152
337
  configuredCsrfMiddleware;
338
+ responses;
339
+ persistence;
153
340
  constructor(dependencies) {
154
341
  this.dependencies = dependencies;
342
+ const http = dependencies.container.has(HTTP_PERSISTENCE_OPTIONS) ? dependencies.container.resolve(HTTP_PERSISTENCE_OPTIONS) : undefined;
343
+ this.httpOptions = http;
344
+ const config = dependencies.container.has(CORE_CONFIG_TOKEN) ? dependencies.container.resolve(CORE_CONFIG_TOKEN) : undefined;
345
+ const features = http?.features ?? config?.get("http.features");
346
+ this.emailVerificationRequired = features?.emailVerificationRequired ?? false;
347
+ this.viewsEnabled = features?.viewsEnabled ?? false;
348
+ this.publicReadsEnabled = features?.publicReadsEnabled ?? false;
349
+ this.etagEnabled = features?.etagEnabled ?? true;
350
+ const policy = http?.responsePolicy ?? config?.get("http.responsePolicy");
351
+ if (policy?.cors)
352
+ resolveCorsConfig(policy.cors);
353
+ this.responsePolicy = Object.freeze({
354
+ cors: policy?.cors ? {
355
+ allowedOrigins: [...policy.cors.allowedOrigins ?? []],
356
+ additionalAllowedHeaders: [...policy.cors.additionalAllowedHeaders ?? []]
357
+ } : undefined,
358
+ securityHeaders: policy?.securityHeaders ?? {
359
+ production: http?.production ?? true,
360
+ frontendMode: this.viewsEnabled ? "server-htmx" : "api"
361
+ },
362
+ maxBodyBytes: policy?.maxBodyBytes ?? 1048576,
363
+ rateLimitPerMinute: policy?.rateLimitPerMinute ?? 120,
364
+ namespace: policy?.namespace ?? "strata",
365
+ trustForwardedFor: policy?.trustForwardedFor ?? false,
366
+ loginRateLimit: Object.freeze({ ...policy?.loginRateLimit ?? resolveLoginRateLimit() }),
367
+ registerRateLimit: Object.freeze({
368
+ ...policy?.registerRateLimit ?? resolveRegisterRateLimit()
369
+ })
370
+ });
155
371
  const targetOrigin = dependencies.container.has(CORE_CONFIG_TOKEN) ? dependencies.container.resolve(CORE_CONFIG_TOKEN).get(CSRF_TARGET_ORIGIN_CONFIG_KEY) : undefined;
156
- this.configuredCsrfMiddleware = createCsrfMiddleware({ targetOrigin });
372
+ this.configuredCsrfMiddleware = createCsrfMiddleware({ targetOrigin, ...http?.csrf });
373
+ this.responses = Object.freeze({
374
+ json: Object.freeze(this.responseMiddleware("json")),
375
+ web: Object.freeze(this.responseMiddleware("web"))
376
+ });
377
+ this.persistence = dependencies.container.has(HTTP_PERSISTENCE_OPTIONS) ? createHttpPersistence(dependencies.invoke, dependencies.container.resolve(HTTP_PERSISTENCE_OPTIONS)) : undefined;
157
378
  if (dependencies.container.has(CORE_HTTP_CLEANUP_TOKEN)) {
158
379
  dependencies.container.resolve(CORE_HTTP_CLEANUP_TOKEN)(() => this.dispose());
159
380
  }
160
381
  }
382
+ requireFlashOptions() {
383
+ const options = this.httpOptions?.flash;
384
+ if (!options)
385
+ throw new TypeError("Explicit flash configuration is required for web routes.");
386
+ return options;
387
+ }
388
+ requireIntendedOptions() {
389
+ const options = this.httpOptions?.intendedUrl;
390
+ if (!options)
391
+ throw new TypeError("Explicit intended URL cookie configuration is required for web authentication.");
392
+ return options;
393
+ }
394
+ routeModelBindingPorts(auth) {
395
+ const gate = this.dependencies.container.resolve(CORE_POLICY_GATE_TOKEN);
396
+ const authorize = gate.authorize;
397
+ return Object.freeze({
398
+ auth,
399
+ authorize: (...args) => authorize.call(gate, ...args),
400
+ etagEnabled: this.etagEnabled
401
+ });
402
+ }
161
403
  dispose() {
162
404
  this.disposed = true;
163
405
  const owned = [...this.ownedThrottles];
@@ -185,39 +427,73 @@ class HttpKernel {
185
427
  return throttle;
186
428
  }
187
429
  globalMiddleware(errorFormat = "json") {
188
- const auth = this.dependencies.container.resolve(CORE_AUTH_TOKEN);
189
- return [
190
- ...this.responseMiddleware(errorFormat),
191
- createAuthMiddleware(auth),
192
- createMembershipMiddleware(),
193
- createTenantMiddleware({
194
- publicTenancy: this.dependencies.container.has(CORE_PUBLIC_TENANCY_TOKEN) ? this.dependencies.container.resolve(CORE_PUBLIC_TENANCY_TOKEN) : undefined,
195
- resolveTenant: this.dependencies.container.has(CORE_TENANT_RESOLVER_TOKEN) ? this.dependencies.container.resolve(CORE_TENANT_RESOLVER_TOKEN) : undefined
196
- })
197
- ];
430
+ return [...this.responses[errorFormat]];
431
+ }
432
+ run(request, handler, format = "json", identity, scim) {
433
+ assertHttpHandler(handler);
434
+ const execute = this.persistence;
435
+ if (!execute)
436
+ throw new Error("Explicit HTTP persistence composition is required.");
437
+ const outer = withMiddleware(...this.responses[format])((req) => withMiddleware(...scim ?? [])((req) => execute(req, handler, identity, scim !== undefined))(req));
438
+ return Promise.resolve(outer(request));
439
+ }
440
+ composed(handler, format, identity = identityModes(handler), scim = scimMiddleware(handler)) {
441
+ assertHttpHandler(handler);
442
+ if (identity !== undefined && scim !== undefined)
443
+ throw new TypeError("SCIM and identity operation declarations cannot be combined.");
444
+ return ownedHttpRoute(handler, (request, work) => this.run(request, work, format, identity, scim), identity, scim);
445
+ }
446
+ wrapIdentity(handler, modes = ["identifier"]) {
447
+ assertHttpHandler(handler);
448
+ if (scimMiddleware(handler) !== undefined)
449
+ throw new TypeError("SCIM and identity operation declarations cannot be combined.");
450
+ if (!Array.isArray(modes) || modes.some((mode) => mode !== "identifier" && mode !== "bypass"))
451
+ throw new TypeError("Invalid identity route policy modes.");
452
+ return this.composed(handler, "web", Object.freeze([...modes]));
453
+ }
454
+ wrapPasswordConfirm(handler) {
455
+ assertHttpHandler(handler);
456
+ const options = this.dependencies.container.resolve(HTTP_PERSISTENCE_OPTIONS).passwordConfirmation;
457
+ if (!options)
458
+ throw new Error("Explicit password confirmation configuration is required.");
459
+ return this.composed(withMiddleware(createRequirePasswordConfirmMiddleware(options))(handler), "json", identityModes(handler), scimMiddleware(handler));
460
+ }
461
+ wrapRouteMap(routes, middleware) {
462
+ return enterModuleRoutes(routes, (callback) => this.composed(withMiddleware(...middleware)(callback), "json", identityModes(callback), scimMiddleware(callback)));
463
+ }
464
+ wrapScim(handler, before = []) {
465
+ assertHttpHandler(handler);
466
+ if (identityModes(handler) !== undefined)
467
+ throw new TypeError("SCIM and identity operation declarations cannot be combined.");
468
+ return this.composed(handler, "json", undefined, Object.freeze([...before]));
198
469
  }
199
470
  responseMiddleware(errorFormat) {
200
471
  return [
201
- createCorsMiddleware(),
202
- createSecurityHeadersMiddleware(),
203
- createBodySizeLimitMiddleware(),
204
- createTracingMiddleware(),
472
+ createCorsMiddleware(this.responsePolicy.cors),
473
+ createSecurityHeadersMiddleware(this.responsePolicy.securityHeaders),
474
+ createBodySizeLimitMiddleware(this.responsePolicy.maxBodyBytes),
475
+ ...this.dependencies.container.has(CORE_TRACING_RUNTIME_TOKEN) ? [createTracingMiddleware(this.dependencies.container.resolve(CORE_TRACING_RUNTIME_TOKEN))] : [],
205
476
  createMetricsMiddleware(),
206
- createRequestLoggingMiddleware(),
477
+ createRequestLoggingMiddleware(this.responsePolicy.trustForwardedFor),
207
478
  requestIdMiddleware,
208
- errorFormat === "json" ? createJsonErrorMiddleware() : createWebErrorMiddleware()
479
+ errorFormat === "json" ? createJsonErrorMiddleware() : createWebErrorMiddleware({
480
+ enabled: this.viewsEnabled,
481
+ production: this.dependencies.container.has(HTTP_PERSISTENCE_OPTIONS) ? this.dependencies.container.resolve(HTTP_PERSISTENCE_OPTIONS).production ?? true : true,
482
+ render: this.dependencies.container.has(CORE_WEB_ERROR_VIEW_TOKEN) ? this.dependencies.container.resolve(CORE_WEB_ERROR_VIEW_TOKEN) : undefined
483
+ })
209
484
  ];
210
485
  }
211
486
  wrapPublicDocument(handler) {
212
- return withMiddleware(...this.responseMiddleware("web"))(handler);
487
+ assertHttpHandler(handler);
488
+ return ownedPublicHttpRoute(handler, (request, work) => Promise.resolve(withMiddleware(...this.responses.web)(work)(request)));
213
489
  }
214
490
  group(name) {
215
- const auth = this.dependencies.container.resolve(CORE_AUTH_TOKEN);
491
+ const auth = establishedAuthReader2;
216
492
  switch (name) {
217
493
  case "authenticated":
218
494
  return [createRequireAuthMiddleware(auth)];
219
495
  case "web":
220
- return isViewsEnabled() ? [createFlashMiddleware(), this.configuredCsrfMiddleware] : [];
496
+ return this.viewsEnabled ? [createFlashMiddleware(this.requireFlashOptions()), this.configuredCsrfMiddleware] : [];
221
497
  case "api": {
222
498
  const csrf = this.configuredCsrfMiddleware;
223
499
  if (!this.dependencies.container.has(CORE_CONFIG_TOKEN)) {
@@ -227,9 +503,11 @@ class HttpKernel {
227
503
  const config = this.dependencies.container.resolve(CORE_CONFIG_TOKEN);
228
504
  const redisUrl = config.get(REDIS_URL_CONFIG_KEY)?.trim() ?? "";
229
505
  if (!redisUrl) {
230
- const maxAttempts = Number(process.env.RATE_LIMIT_PER_MINUTE ?? "120");
506
+ const maxAttempts = this.responsePolicy.rateLimitPerMinute ?? 120;
231
507
  return [
232
508
  this.ownThrottle(createMemoryThrottleMiddleware({
509
+ namespace: this.responsePolicy.namespace,
510
+ trustForwardedFor: this.responsePolicy.trustForwardedFor,
233
511
  maxAttempts: Number.isFinite(maxAttempts) ? maxAttempts : 120,
234
512
  decaySeconds: 60,
235
513
  quotaPolicy
@@ -237,9 +515,11 @@ class HttpKernel {
237
515
  csrf
238
516
  ];
239
517
  }
240
- const maxAttempts = Number(process.env.RATE_LIMIT_PER_MINUTE ?? "120");
518
+ const maxAttempts = this.responsePolicy.rateLimitPerMinute ?? 120;
241
519
  return [
242
520
  this.ownThrottle(createThrottleMiddleware({
521
+ namespace: this.responsePolicy.namespace,
522
+ trustForwardedFor: this.responsePolicy.trustForwardedFor,
243
523
  redisUrl,
244
524
  maxAttempts: Number.isFinite(maxAttempts) ? maxAttempts : 120,
245
525
  decaySeconds: 60,
@@ -253,496 +533,430 @@ class HttpKernel {
253
533
  }
254
534
  }
255
535
  wrap(groups, handler) {
536
+ assertHttpHandler(handler);
256
537
  const names = Array.isArray(groups) ? groups : [groups];
257
538
  const middleware = names.flatMap((name) => this.group(name));
258
539
  const wrapped = middleware.length === 0 ? handler : withMiddleware(...middleware)(handler);
259
540
  if (names.includes("api")) {
260
- return withJsonErrorHandling(wrapped);
541
+ return this.composed(wrapped, "json", identityModes(handler), scimMiddleware(handler));
261
542
  }
262
- return wrapped;
543
+ return this.composed(wrapped, "web", identityModes(handler), scimMiddleware(handler));
263
544
  }
264
545
  wrapApi(handler) {
546
+ assertHttpHandler(handler);
265
547
  return this.wrap(["api", "authenticated"], handler);
266
548
  }
267
549
  wrapWeb(handler) {
268
- return withErrorHandling(this.wrap("web", handler));
550
+ assertHttpHandler(handler);
551
+ return this.wrap("web", handler);
269
552
  }
270
553
  wrapWebGuest(handler, home = "/") {
271
- const auth = this.dependencies.container.resolve(CORE_AUTH_TOKEN);
272
- return this.wrapWeb(async (request) => {
554
+ assertHttpHandler(handler);
555
+ const auth = establishedAuthReader2;
556
+ const guest = this.wrapWeb(async (request, ports) => {
273
557
  const user = await auth.resolve(request);
274
558
  if (user) {
275
- if (isEmailVerificationRequired() && !hasVerifiedEmail(user)) {
559
+ if (this.emailVerificationRequired && !hasVerifiedEmail(user)) {
276
560
  return Response.redirect("/email/verify", 302);
277
561
  }
278
562
  const location = typeof home === "function" ? await home(user) : home;
279
563
  return Response.redirect(location, 302);
280
564
  }
281
- return handler(request);
565
+ return handler(request, ports);
282
566
  });
567
+ return this.composed(guest, "web", identityModes(handler), scimMiddleware(handler));
283
568
  }
284
569
  wrapWebPublicRead(handler, options = {}) {
285
- if (options.allowAnonymous ?? isPublicReadsEnabled()) {
570
+ assertHttpHandler(handler);
571
+ if (options.allowAnonymous ?? this.publicReadsEnabled) {
286
572
  return this.wrapWeb(handler);
287
573
  }
288
574
  return this.wrapWebAuthenticated(handler);
289
575
  }
290
576
  wrapWebAuthenticated(handler) {
577
+ assertHttpHandler(handler);
291
578
  return this.wrapWebAuth(handler, { verified: true });
292
579
  }
293
580
  wrapWebAuthenticatedAllowUnverified(handler) {
581
+ assertHttpHandler(handler);
294
582
  return this.wrapWebAuth(handler, { verified: false });
295
583
  }
296
584
  wrapWebVerified(handler) {
585
+ assertHttpHandler(handler);
297
586
  return this.wrapWebAuth(handler, { verified: true });
298
587
  }
299
588
  wrapWebPasswordConfirm(handler) {
300
- return this.wrapWebAuth(withMiddleware(createRequirePasswordConfirmMiddleware())(handler), {
589
+ assertHttpHandler(handler);
590
+ const options = this.dependencies.container.resolve(HTTP_PERSISTENCE_OPTIONS).passwordConfirmation;
591
+ if (!options)
592
+ throw new Error("Explicit password confirmation configuration is required.");
593
+ return this.wrapWebAuth(this.composed(withMiddleware(createRequirePasswordConfirmMiddleware(options))(handler), "web", identityModes(handler), scimMiddleware(handler)), {
301
594
  verified: true
302
595
  });
303
596
  }
304
597
  wrapWebAbility(ability, handler) {
305
- const auth = this.dependencies.container.resolve(CORE_AUTH_TOKEN);
598
+ assertHttpHandler(handler);
599
+ const auth = establishedAuthReader2;
306
600
  const abilityChecker = resolveAbilityChecker(this.dependencies.container);
307
- const requireAbility = createRequireAbilityMiddleware(abilityChecker);
601
+ const requireAbility = createRequireAbilityMiddleware(abilityChecker, this.viewsEnabled);
308
602
  const middleware = [
309
- createRequireWebAuthMiddleware(auth),
603
+ createRequireWebAuthMiddleware(auth, this.requireIntendedOptions()),
310
604
  ...this.verifiedMiddleware(),
311
605
  requireAbility(ability)
312
606
  ];
313
- return this.wrapWeb(withMiddleware(...middleware)(handler));
607
+ return this.wrapWeb(this.composed(withMiddleware(...middleware)(handler), "web", identityModes(handler), scimMiddleware(handler)));
314
608
  }
315
609
  wrapWebGlobalAdmin(handler) {
316
- const auth = this.dependencies.container.resolve(CORE_AUTH_TOKEN);
610
+ assertHttpHandler(handler);
611
+ const auth = establishedAuthReader2;
317
612
  const middleware = [
318
- createRequireWebAuthMiddleware(auth),
613
+ createRequireWebAuthMiddleware(auth, this.requireIntendedOptions()),
319
614
  ...this.verifiedMiddleware(),
320
615
  createRequireGlobalAdminMiddleware()
321
616
  ];
322
- return this.wrapWeb(withMiddleware(...middleware)(handler));
617
+ return this.wrapWeb(this.composed(withMiddleware(...middleware)(handler), "web", identityModes(handler), scimMiddleware(handler)));
323
618
  }
324
619
  wrapAuthenticated(handler) {
620
+ assertHttpHandler(handler);
325
621
  return this.wrap("authenticated", handler);
326
622
  }
327
623
  wrapVerified(handler) {
624
+ assertHttpHandler(handler);
328
625
  const middleware = [...this.group("authenticated"), ...this.verifiedMiddleware()];
329
- return withMiddleware(...middleware)(handler);
626
+ return this.composed(withMiddleware(...middleware)(handler), "json", identityModes(handler), scimMiddleware(handler));
330
627
  }
331
628
  wrapPublicRead(handler, options = {}) {
332
- if (options.allowAnonymous ?? isPublicReadsEnabled()) {
333
- return handler;
629
+ assertHttpHandler(handler);
630
+ if (options.allowAnonymous ?? this.publicReadsEnabled) {
631
+ return this.composed(handler, "json");
334
632
  }
335
633
  return this.wrapAuthenticated(handler);
336
634
  }
337
635
  wrapGlobalAdmin(handler) {
636
+ assertHttpHandler(handler);
338
637
  const middleware = [...this.group("authenticated"), createRequireGlobalAdminMiddleware()];
339
- return withMiddleware(...middleware)(handler);
638
+ return this.composed(withMiddleware(...middleware)(handler), "json", identityModes(handler), scimMiddleware(handler));
340
639
  }
341
640
  wrapAbility(ability, handler) {
641
+ assertHttpHandler(handler);
342
642
  const abilityChecker = resolveAbilityChecker(this.dependencies.container);
343
- const requireAbility = createRequireAbilityMiddleware(abilityChecker);
643
+ const requireAbility = createRequireAbilityMiddleware(abilityChecker, this.viewsEnabled);
344
644
  const middleware = [...this.group("authenticated"), requireAbility(ability)];
345
- return withMiddleware(...middleware)(handler);
645
+ return this.composed(withMiddleware(...middleware)(handler), "json", identityModes(handler), scimMiddleware(handler));
346
646
  }
347
647
  wrapPolicy(resource, action, handler) {
348
- const auth = this.dependencies.container.resolve(CORE_AUTH_TOKEN);
648
+ assertHttpHandler(handler);
649
+ const auth = establishedAuthReader2;
349
650
  const gate = this.dependencies.container.resolve(CORE_POLICY_GATE_TOKEN);
350
- return withMiddleware(createAuthorizeMiddleware(gate, auth, resource, action))(handler);
651
+ return this.composed(withMiddleware(createAuthorizeMiddleware(gate, auth, resource, action))(handler), "json", identityModes(handler), scimMiddleware(handler));
351
652
  }
352
653
  wrapLogin(handler) {
353
- return this.wrapThrottle("login", resolveLoginRateLimit(), handler);
654
+ assertHttpHandler(handler);
655
+ return this.wrapThrottle("login", this.responsePolicy.loginRateLimit ?? resolveLoginRateLimit(), handler);
354
656
  }
355
657
  wrapSigned(handler) {
356
- return withMiddleware(createValidateSignatureMiddleware())(handler);
658
+ assertHttpHandler(handler);
659
+ const secret = this.dependencies.container.resolve(HTTP_PERSISTENCE_OPTIONS).signatureSecret;
660
+ if (!secret)
661
+ throw new Error("Explicit signed URL configuration is required.");
662
+ return this.composed(withMiddleware(createValidateSignatureMiddleware({ secret }))(handler), "json", identityModes(handler), scimMiddleware(handler));
357
663
  }
358
664
  wrapRegister(handler) {
359
- return this.wrapThrottle("register", resolveRegisterRateLimit(), handler);
665
+ assertHttpHandler(handler);
666
+ return this.wrapThrottle("register", this.responsePolicy.registerRateLimit ?? resolveRegisterRateLimit(), handler);
360
667
  }
361
668
  wrapWebAuth(handler, options) {
362
- const auth = this.dependencies.container.resolve(CORE_AUTH_TOKEN);
669
+ assertHttpHandler(handler);
670
+ const auth = establishedAuthReader2;
363
671
  const middleware = [
364
- createRequireWebAuthMiddleware(auth),
672
+ createRequireWebAuthMiddleware(auth, this.requireIntendedOptions()),
365
673
  ...options.verified ? this.verifiedMiddleware() : []
366
674
  ];
367
- return this.wrapWeb(withMiddleware(...middleware)(handler));
675
+ return this.wrapWeb(this.composed(withMiddleware(...middleware)(handler), "web", identityModes(handler), scimMiddleware(handler)));
368
676
  }
369
677
  verifiedMiddleware() {
370
- const auth = this.dependencies.container.resolve(CORE_AUTH_TOKEN);
371
- return [createRequireVerifiedMiddleware(auth)];
678
+ const auth = establishedAuthReader2;
679
+ return [
680
+ createRequireVerifiedMiddleware(auth, this.emailVerificationRequired, this.requireIntendedOptions())
681
+ ];
372
682
  }
373
683
  wrapThrottle(scope, rateLimit, handler) {
684
+ assertHttpHandler(handler);
374
685
  const memoryKeyPrefix = scope === "login" ? "login-throttle:" : "register-throttle:";
375
686
  const redisUrl = this.dependencies.container.has(CORE_CONFIG_TOKEN) ? this.dependencies.container.resolve(CORE_CONFIG_TOKEN).get(REDIS_URL_CONFIG_KEY)?.trim() ?? "" : "";
376
687
  if (scope === "login") {
377
- return withMiddleware(this.ownThrottle(createLoginThrottleMiddleware({
688
+ return this.composed(withMiddleware(this.ownThrottle(createLoginThrottleMiddleware({
689
+ namespace: this.responsePolicy.namespace,
690
+ trustForwardedFor: this.responsePolicy.trustForwardedFor,
378
691
  ...redisUrl ? { redisUrl } : {},
379
692
  maxAttempts: rateLimit.maxAttempts,
380
693
  decaySeconds: rateLimit.decaySeconds
381
- })))(handler);
694
+ })))(handler), "json", identityModes(handler), scimMiddleware(handler));
382
695
  }
383
696
  if (redisUrl) {
384
- return withMiddleware(this.ownThrottle(createThrottleMiddleware({
697
+ return this.composed(withMiddleware(this.ownThrottle(createThrottleMiddleware({
698
+ namespace: this.responsePolicy.namespace,
699
+ trustForwardedFor: this.responsePolicy.trustForwardedFor,
385
700
  redisUrl,
386
701
  maxAttempts: rateLimit.maxAttempts,
387
702
  decaySeconds: rateLimit.decaySeconds,
388
703
  keyPrefix: memoryKeyPrefix
389
- })))(handler);
704
+ })))(handler), "json", identityModes(handler), scimMiddleware(handler));
390
705
  }
391
- return withMiddleware(this.ownThrottle(createMemoryThrottleMiddleware({
706
+ return this.composed(withMiddleware(this.ownThrottle(createMemoryThrottleMiddleware({
707
+ namespace: this.responsePolicy.namespace,
708
+ trustForwardedFor: this.responsePolicy.trustForwardedFor,
392
709
  maxAttempts: rateLimit.maxAttempts,
393
710
  decaySeconds: rateLimit.decaySeconds,
394
711
  keyPrefix: memoryKeyPrefix
395
- })))(handler);
712
+ })))(handler), "json", identityModes(handler), scimMiddleware(handler));
396
713
  }
397
714
  }
398
715
  function createHttpKernel(dependencies) {
399
716
  return new HttpKernel(dependencies);
400
717
  }
401
718
 
402
- // ../../src/bootstrap/moduleRouteMiddleware.ts
403
- import { applyMiddlewareToRoutes } from "@getstrata/core/http/middleware";
404
- function wrapCallback(path, callback, middleware) {
405
- return applyMiddlewareToRoutes({ [path]: callback }, middleware)[path];
406
- }
407
- function applyModuleRouteMiddleware(routes, middleware) {
408
- const wrapped = {};
409
- for (const [path, value] of Object.entries(routes)) {
410
- if (value instanceof Response) {
411
- const methods = {};
412
- for (const method of ["GET", "HEAD", "POST", "PUT", "DELETE", "PATCH", "OPTIONS"]) {
413
- methods[method] = wrapCallback(path, () => value.clone(), middleware);
414
- }
415
- wrapped[path] = methods;
416
- continue;
417
- }
418
- if (typeof value === "function") {
419
- wrapped[path] = wrapCallback(path, value, middleware);
420
- continue;
421
- }
422
- if (value && typeof value === "object" && !Array.isArray(value)) {
423
- const entries = Object.entries(value);
424
- if (entries.some(([, handler]) => typeof handler === "function" || handler instanceof Response)) {
425
- wrapped[path] = Object.fromEntries(entries.map(([method, handler]) => {
426
- const callback = handler instanceof Response ? () => handler.clone() : handler;
427
- return [
428
- method,
429
- typeof callback === "function" ? wrapCallback(path, callback, middleware) : callback
430
- ];
431
- }));
432
- continue;
433
- }
434
- }
435
- wrapped[path] = value;
436
- }
437
- return wrapped;
438
- }
439
-
440
- // ../../src/bootstrap/discoverModules.ts
441
- import { readdir as readdir2 } from "fs/promises";
442
- import { join as join2, resolve } from "path";
443
-
444
- // ../../src/bootstrap/infrastructureDiscovery.ts
445
- import { readdir } from "fs/promises";
446
- import { join, relative } from "path";
447
- import { pathToFileURL } from "url";
448
- async function infrastructureFiles(directory, exclude = []) {
449
- const excluded = new Set([
450
- "index.ts",
451
- "index.js",
452
- "index.mts",
453
- "index.mjs",
454
- "register.ts",
455
- "register.js",
456
- "register.mts",
457
- "register.mjs",
458
- ...exclude
459
- ]);
460
- const files = [];
461
- async function visit(path) {
462
- const entries = await readdir(path, { withFileTypes: true });
463
- entries.sort((a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0);
464
- for (const entry of entries) {
465
- const file = join(path, entry.name);
466
- const key = relative(directory, file).replaceAll("\\", "/");
467
- if (excluded.has(entry.name) || excluded.has(key))
468
- continue;
469
- if (entry.isDirectory())
470
- await visit(file);
471
- else if (entry.isFile() && /\.(ts|js|mts|mjs)$/.test(entry.name) && !/\.(d|test|spec)\.[cm]?[jt]s$/.test(entry.name))
472
- files.push(file);
719
+ // ../../src/bootstrap/routeCompiler.ts
720
+ var ROUTE_METHODS = ["GET", "HEAD", "POST", "PUT", "DELETE", "PATCH", "OPTIONS"];
721
+ var OPENAPI_METHODS = new Set([...ROUTE_METHODS, "TRACE"]);
722
+ var inventoryKey = Symbol.for("@getstrata/owned-route-inventory");
723
+ function readRouteInventory(routes) {
724
+ return Object.getOwnPropertyDescriptor(routes, inventoryKey)?.value;
725
+ }
726
+ function immutableCopy(value, ancestors = new Set) {
727
+ if (value === null || typeof value !== "object") {
728
+ if (typeof value === "function" || typeof value === "symbol" || typeof value === "bigint" || typeof value === "number" && !Number.isFinite(value)) {
729
+ throw new Error("Route metadata must contain only JSON values");
473
730
  }
731
+ return value;
474
732
  }
475
- try {
476
- await visit(directory);
477
- } catch (error) {
478
- if (error.code !== "ENOENT")
479
- throw error;
480
- if (error.path !== directory)
481
- throw error;
733
+ if (ancestors.has(value))
734
+ throw new Error("Route metadata must not contain cycles");
735
+ if (!Array.isArray(value) && Object.getPrototypeOf(value) !== Object.prototype && Object.getPrototypeOf(value) !== null) {
736
+ throw new Error("Route metadata must contain only JSON objects");
482
737
  }
483
- return files;
738
+ ancestors.add(value);
739
+ const copy = Array.isArray(value) ? value.map((entry) => immutableCopy(entry, ancestors)) : Object.fromEntries(Object.entries(value).map(([key, entry]) => [key, immutableCopy(entry, ancestors)]));
740
+ ancestors.delete(value);
741
+ return Object.freeze(copy);
484
742
  }
485
- async function importInfrastructure(file) {
486
- try {
487
- return await import(pathToFileURL(file).href);
488
- } catch (error) {
489
- throw new Error(`Cannot load infrastructure module ${file}`, { cause: error });
743
+ function normalizeRoutePath(path, prefix = "") {
744
+ const normalizedPrefix = prefix.replace(/\/+$/, "");
745
+ const normalizedPath = path.startsWith("/") ? path : `/${path}`;
746
+ const result = `${normalizedPrefix ? normalizedPrefix.startsWith("/") ? normalizedPrefix : `/${normalizedPrefix}` : ""}${normalizedPath}`;
747
+ if (!path || /[?#\s]/.test(result) || result.includes("//") || result.split("/").some((part) => part === "." || part === "..")) {
748
+ throw new Error(`Invalid route path: ${path}`);
490
749
  }
750
+ return result;
491
751
  }
492
-
493
- // ../../src/bootstrap/discoverModules.ts
494
- var KEY = Symbol.for("@getstrata/discoverModulesState");
495
- function state() {
496
- const globals = globalThis;
497
- globals[KEY] ??= { appModules: [] };
498
- return globals[KEY];
499
- }
500
- function configureModulesDirectory(modulesDir) {
501
- const current = state();
502
- const directory = resolve(modulesDir);
503
- if (current.configuredModulesDir !== directory || current.configuredManifest) {
504
- current.appModules.length = 0;
505
- current.modulesReady = undefined;
506
- current.source = undefined;
507
- }
508
- current.configuredManifest = undefined;
509
- current.configuredModulesDir = directory;
510
- }
511
- function configureModulesManifest(manifest) {
512
- const current = state();
513
- if (current.configuredManifest !== manifest) {
514
- current.appModules.length = 0;
515
- current.modulesReady = undefined;
516
- current.source = undefined;
517
- }
518
- current.configuredManifest = manifest;
519
- }
520
- function validateModule(value, location) {
521
- if (!value || typeof value !== "object" || Array.isArray(value))
522
- throw new TypeError(`Invalid application module at ${location}.`);
523
- const module = value;
524
- if (typeof module.name !== "string" || !module.name.trim())
525
- throw new TypeError(`Invalid module name at ${location}.`);
526
- if (module.order !== undefined && (typeof module.order !== "number" || !Number.isFinite(module.order)))
527
- throw new TypeError(`Invalid module order at ${location}.`);
528
- for (const hook of ["routes", "webRoutes"])
529
- if (module[hook] !== undefined && typeof module[hook] !== "function")
530
- throw new TypeError(`Invalid ${hook} at ${location}.`);
531
- if (module.providers !== undefined) {
532
- if (!Array.isArray(module.providers))
533
- throw new TypeError(`Invalid providers at ${location}.`);
534
- for (const provider of module.providers) {
535
- if (!provider || typeof provider.name !== "string" || !provider.name.trim() || provider.register !== undefined && typeof provider.register !== "function" || provider.boot !== undefined && typeof provider.boot !== "function")
536
- throw new TypeError(`Invalid provider at ${location}.`);
752
+ function routeMethods(handler) {
753
+ if (handler === false)
754
+ return { methods: [], handler };
755
+ if (handler instanceof Response)
756
+ return {
757
+ methods: [...ROUTE_METHODS],
758
+ handler: Object.freeze(Object.fromEntries(ROUTE_METHODS.map((method) => [method, handler])))
759
+ };
760
+ if (typeof handler === "function")
761
+ return { methods: ["*"], handler };
762
+ if (handler && typeof handler === "object" && !Array.isArray(handler)) {
763
+ const entries = Object.entries(handler);
764
+ if (entries.some(([method, value]) => OPENAPI_METHODS.has(method.toUpperCase()) || typeof value === "function" || value instanceof Response)) {
765
+ const methods = {};
766
+ for (const [rawMethod, value] of entries) {
767
+ const method = rawMethod.toUpperCase();
768
+ if (!ROUTE_METHODS.includes(method)) {
769
+ throw new Error(`Unsupported route method: ${rawMethod}`);
770
+ }
771
+ if (Object.hasOwn(methods, method))
772
+ throw new Error(`Duplicate route method: ${method}`);
773
+ if (typeof value !== "function" && !(value instanceof Response)) {
774
+ throw new Error(`Invalid route handler: ${method}`);
775
+ }
776
+ methods[method] = value;
777
+ }
778
+ return { methods: Object.keys(methods), handler: Object.freeze(methods) };
537
779
  }
538
- }
539
- }
540
- async function load(options) {
541
- const manifest = options.manifest ?? (options.modulesDir === undefined ? state().configuredManifest : undefined);
542
- const entries = [];
543
- if (manifest)
544
- for (const [index, value] of manifest.entries())
545
- entries.push({ value, location: `module manifest[${index}]` });
546
- else {
547
- const directory = options.modulesDir ?? state().configuredModulesDir;
548
- if (!directory)
549
- throw new Error("configureModulesDirectory() or configureModulesManifest() must be called before discovering modules.");
550
- let folders;
551
- try {
552
- folders = await readdir2(directory, { withFileTypes: true });
553
- } catch (error) {
554
- if (error.code === "ENOENT")
555
- return [];
556
- throw error;
780
+ if (Object.prototype.toString.call(handler) === "[object HTMLBundle]") {
781
+ return { methods: ["GET", "HEAD"], handler };
557
782
  }
558
- const excluded = new Set(options.exclude ?? []);
559
- for (const folder of folders.filter((entry) => entry.isDirectory() && !excluded.has(entry.name)).sort((a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0)) {
560
- const path = join2(directory, folder.name);
561
- const files = await readdir2(path);
562
- const candidates = files.filter((file) => /^index\.(ts|js|mts|mjs)$/.test(file));
563
- if (candidates.length !== 1)
564
- throw new Error(`Expected one module entrypoint at ${path}; found ${candidates.length}.`);
565
- const file = join2(path, candidates[0]);
566
- const exports = await importInfrastructure(file);
567
- entries.push({ value: exports.default, location: file });
783
+ if (handler instanceof Blob && "exists" in handler && typeof handler.exists === "function") {
784
+ return { methods: ["*"], handler };
785
+ }
786
+ if (Object.getPrototypeOf(handler) === Object.prototype && "dir" in handler && typeof handler.dir === "string" && handler.dir.length > 0 && entries.every(([key, value]) => key === "dir" || key === "statCache" && typeof value === "boolean")) {
787
+ return { methods: ["*"], handler: Object.freeze({ ...handler }) };
788
+ }
789
+ throw new Error("Invalid route method map or native route declaration");
790
+ }
791
+ throw new Error("Invalid route handler");
792
+ }
793
+ function compileRoutePlan(sources, prefix = "") {
794
+ const routes = Object.create(null);
795
+ const owners = new Map;
796
+ const inventory = [];
797
+ const canonicalPaths = new Map;
798
+ const implicitHeads = new Map;
799
+ for (const source of sources) {
800
+ for (const path of Object.keys(source.metadata ?? {})) {
801
+ if (!Object.hasOwn(source.routes, path)) {
802
+ throw new Error(`OpenAPI metadata has no API route: ${source.name} ${path}`);
803
+ }
804
+ }
805
+ for (const [rawPath, rawHandler] of Object.entries(source.routes)) {
806
+ const path = normalizeRoutePath(rawPath, prefix);
807
+ const { methods, handler } = routeMethods(rawHandler);
808
+ if (handler && typeof handler === "object" && "dir" in handler && !path.endsWith("/*")) {
809
+ throw new Error(`Directory route must end in /*: ${path}`);
810
+ }
811
+ const collisionPath = path.replace(/:[^/]+/g, ":parameter");
812
+ const canonicalPath = canonicalPaths.get(collisionPath);
813
+ if (canonicalPath && canonicalPath !== path) {
814
+ throw new Error(`Ambiguous route parameter names: ${canonicalPath} and ${path}`);
815
+ }
816
+ canonicalPaths.set(collisionPath, path);
817
+ const previous = owners.get(collisionPath) ?? new Map;
818
+ for (const method of methods) {
819
+ if (previous.has(method) || previous.has("*") || method === "*" && previous.size) {
820
+ throw new Error(`Duplicate route: ${method} ${path} (${[...previous.values()][0]} and ${source.name})`);
821
+ }
822
+ }
823
+ const metadata = source.metadata?.[rawPath];
824
+ for (const method of Object.keys(metadata ?? {})) {
825
+ if (!OPENAPI_METHODS.has(method) || !methods.includes("*") && !methods.includes(method) && !(method === "HEAD" && methods.includes("GET"))) {
826
+ throw new Error(`OpenAPI metadata has no API handler: ${method} ${rawPath}`);
827
+ }
828
+ }
829
+ const inherited = readRouteInventory(source.routes)?.filter((entry) => entry.path === rawPath);
830
+ if (inherited) {
831
+ inventory.push(...inherited.filter((entry) => entry.method !== "HEAD" || !methods.includes("GET") || methods.includes("HEAD")).map((entry) => ({ ...entry, path })));
832
+ } else {
833
+ for (const method of methods) {
834
+ const openApi = metadata?.[method];
835
+ inventory.push({
836
+ method,
837
+ path,
838
+ middleware: source.middleware ?? [],
839
+ ...openApi ? { openApi } : {}
840
+ });
841
+ }
842
+ if (methods.includes("*")) {
843
+ for (const [method, openApi] of Object.entries(metadata ?? {})) {
844
+ inventory.push({
845
+ method,
846
+ path,
847
+ middleware: source.middleware ?? [],
848
+ ...openApi ? { openApi } : {}
849
+ });
850
+ }
851
+ }
852
+ }
853
+ if (methods.includes("GET") && !methods.includes("HEAD")) {
854
+ const openApi = metadata?.HEAD ?? inherited?.find((entry) => entry.method === "HEAD")?.openApi;
855
+ implicitHeads.set(path, {
856
+ method: "HEAD",
857
+ path,
858
+ middleware: inherited?.find((entry) => entry.method === "GET")?.middleware ?? source.middleware ?? [],
859
+ ...openApi ? { openApi } : {}
860
+ });
861
+ }
862
+ for (const method of methods)
863
+ previous.set(method, source.name);
864
+ owners.set(collisionPath, previous);
865
+ if (Object.hasOwn(routes, path)) {
866
+ if (routes[path] === false || handler === false || Object.prototype.toString.call(routes[path]) === "[object HTMLBundle]" || Object.prototype.toString.call(handler) === "[object HTMLBundle]") {
867
+ throw new Error(`Cannot merge native bundle route: ${path}`);
868
+ }
869
+ routes[path] = Object.freeze({ ...routes[path], ...handler });
870
+ } else {
871
+ routes[path] = handler;
872
+ }
568
873
  }
569
874
  }
570
- const names = new Map;
571
- const modules = [];
572
- for (const { value, location } of entries) {
573
- validateModule(value, location);
574
- const previous = names.get(value.name);
575
- if (previous)
576
- throw new Error(`Duplicate module "${value.name}" at ${location}; first declared at ${previous}.`);
577
- names.set(value.name, location);
578
- modules.push(value);
579
- }
580
- return modules.sort((left, right) => (left.order ?? 100) - (right.order ?? 100));
581
- }
582
- function ensureModulesLoaded(options = {}) {
583
- const current = state();
584
- const key = options.manifest ?? (options.modulesDir === undefined ? current.configuredManifest : undefined) ?? JSON.stringify([
585
- options.modulesDir ? resolve(options.modulesDir) : current.configuredModulesDir,
586
- [...options.exclude ?? []].sort()
587
- ]);
588
- if (current.modulesReady && current.source === key)
589
- return current.modulesReady;
590
- current.appModules.length = 0;
591
- current.source = key;
592
- const pending = load(options).then((modules) => {
593
- if (current.modulesReady !== pending)
594
- return modules;
595
- current.appModules.splice(0, current.appModules.length, ...modules);
596
- return current.appModules;
597
- }).catch((error) => {
598
- if (current.modulesReady === pending)
599
- current.modulesReady = undefined;
600
- throw error;
601
- });
602
- current.modulesReady = pending;
603
- return pending;
604
- }
605
- function discoverModules() {
606
- return state().appModules;
607
- }
608
- // ../../src/bootstrap/prefixRouteMap.ts
609
- function prefixRouteMap(prefix, routes) {
610
- const normalizedPrefix = prefix.replace(/\/$/, "");
611
- const prefixed = {};
612
- for (const [path, handler] of Object.entries(routes)) {
613
- const normalizedPath = path.startsWith("/") ? path : `/${path}`;
614
- prefixed[`${normalizedPrefix}${normalizedPath}`] = handler;
875
+ for (const [path, head] of implicitHeads) {
876
+ if (!inventory.some((entry) => entry.path === path && entry.method === "HEAD"))
877
+ inventory.push(head);
615
878
  }
616
- return prefixed;
879
+ const snapshot = immutableCopy(inventory.sort((left, right) => left.path.localeCompare(right.path)));
880
+ return Object.freeze({ routes: attachRouteInventory(routes, snapshot), inventory: snapshot });
617
881
  }
618
-
619
- // ../../src/bootstrap/routeRegistry.ts
620
- class RouteRegistry {
621
- routes = [];
622
- register(route) {
623
- this.routes.push(route);
624
- }
625
- clear() {
626
- this.routes.length = 0;
627
- }
628
- list() {
629
- return [...this.routes].sort((left, right) => left.path.localeCompare(right.path));
882
+ function attachRouteInventory(routes, inventory) {
883
+ for (const value of Object.values(routes)) {
884
+ if (value && typeof value === "object" && !(value instanceof Response) && Object.keys(value).some((method) => ROUTE_METHODS.includes(method))) {
885
+ Object.freeze(value);
886
+ }
630
887
  }
888
+ Object.defineProperty(routes, inventoryKey, { value: inventory, enumerable: false });
889
+ return Object.freeze(routes);
631
890
  }
632
- var ROUTE_REGISTRY_KEY = Symbol.for("@getstrata/routeRegistry");
633
- function readSharedRouteRegistry() {
634
- const globalRegistry = globalThis[ROUTE_REGISTRY_KEY];
635
- if (globalRegistry) {
636
- return globalRegistry;
637
- }
638
- const registry = new RouteRegistry;
639
- globalThis[ROUTE_REGISTRY_KEY] = registry;
640
- return registry;
891
+ function getRouteInventory(routes) {
892
+ const inventory = readRouteInventory(routes);
893
+ if (!inventory)
894
+ throw new Error("Route map has not been compiled");
895
+ return inventory;
641
896
  }
642
- var routeRegistry = readSharedRouteRegistry();
643
897
 
644
898
  // ../../src/bootstrap/routeMetadata.ts
645
- function registerOpenApiRoute(method, path, middleware, openApi) {
646
- routeRegistry.register({ method, path, middleware, ...openApi ? { openApi } : {} });
647
- }
648
- function registerOpenApiRouteMap(routes, middleware, metadata = {}) {
649
- const registered = {};
650
- for (const [path, handler] of Object.entries(routes)) {
651
- if (handler && typeof handler === "object" && !Array.isArray(handler)) {
652
- const methodMap = handler;
653
- registered[path] = methodMap;
654
- for (const method of Object.keys(methodMap)) {
655
- registerOpenApiRoute(method.toUpperCase(), path, middleware, metadata[path]?.[method.toUpperCase()]);
656
- }
657
- continue;
658
- }
659
- registered[path] = handler;
660
- registerOpenApiRoute("GET", path, middleware, metadata[path]?.GET);
661
- }
662
- return registered;
899
+ function publishRoutePlan(plan, routes = plan.routes) {
900
+ return attachRouteInventory(routes, plan.inventory);
663
901
  }
664
902
 
665
903
  // ../../src/bootstrap/buildModuleRoutes.ts
666
- function prefixApiModuleRoutes(prefix, routes, metadata) {
667
- const entries = Object.fromEntries(Object.entries(routes).map(([path, handler]) => [path, { handler, openApi: metadata[path] }]));
668
- const prefixedRoutes = {};
669
- const prefixedMetadata = {};
670
- for (const [path, entry] of Object.entries(prefixRouteMap(prefix, entries))) {
671
- prefixedRoutes[path] = entry.handler;
672
- if (entry.openApi)
673
- prefixedMetadata[path] = entry.openApi;
674
- }
675
- return { routes: prefixedRoutes, metadata: prefixedMetadata };
676
- }
677
- function buildModuleRoutes(dependencies, options = {}) {
678
- const { apiPrefix = "", modules = discoverModules(), clearRegistry = true } = options;
679
- if (clearRegistry) {
680
- routeRegistry.clear();
681
- }
904
+ function buildModuleRoutes(dependencies, options) {
905
+ const { apiPrefix = "", modules } = options;
682
906
  const kernel = createHttpKernel(dependencies);
683
- const middleware = [...kernel.globalMiddleware(), ...kernel.group("api")];
684
- const cachedJson = createCachedJson(dependencies);
685
- const moduleRoutes = {};
686
- const metadata = {};
907
+ const middleware = kernel.group("api");
908
+ const cachedJson = createApplicationCachedJson(dependencies);
909
+ const sources = [];
687
910
  for (const module of modules) {
688
- if (!module.routes) {
911
+ if (!module.routes && !module.openApi) {
689
912
  continue;
690
913
  }
691
- const routes = module.routes({ dependencies, cachedJson, kernel });
692
- for (const [path, operations] of Object.entries(module.openApi ?? {})) {
693
- if (!(path in routes))
694
- throw new Error(`OpenAPI metadata has no API route: ${module.name} ${path}`);
695
- const methods = typeof routes[path] === "function" ? ["GET"] : Object.keys(routes[path]).map((method) => method.toUpperCase());
696
- for (const method of Object.keys(operations))
697
- if (!methods.includes(method))
698
- throw new Error(`OpenAPI metadata has no API handler: ${method} ${path}`);
699
- }
700
- for (const path of Object.keys(routes)) {
701
- delete metadata[path];
702
- if (module.openApi?.[path])
703
- metadata[path] = module.openApi[path];
704
- }
705
- Object.assign(moduleRoutes, routes);
914
+ sources.push({
915
+ name: module.name,
916
+ routes: module.routes?.({ dependencies, cachedJson, kernel }) ?? {},
917
+ metadata: module.openApi,
918
+ middleware: ["global", "api"]
919
+ });
706
920
  }
707
- const prefixed = prefixApiModuleRoutes(apiPrefix, moduleRoutes, metadata);
708
- return applyModuleRouteMiddleware(registerOpenApiRouteMap(prefixed.routes, ["global", "api"], prefixed.metadata), middleware);
921
+ const plan = compileRoutePlan(sources, apiPrefix);
922
+ const routes = enterModuleRoutes(plan.routes, (callback) => kernel.composed(withMiddleware2(...middleware)(callback), "json", identityModes2(callback), scimMiddleware2(callback)));
923
+ return publishRoutePlan(plan, routes);
709
924
  }
710
925
  // ../../src/bootstrap/buildWebModuleRoutes.ts
711
- function buildWebModuleRoutes(dependencies, options = {}) {
712
- const { modules = discoverModules(), clearRegistry = true, seedRoutes = {} } = options;
713
- if (clearRegistry) {
714
- routeRegistry.clear();
715
- }
926
+ function buildWebModuleRoutes(dependencies, options) {
927
+ const { modules, seedRoutes = {} } = options;
716
928
  const kernel = createHttpKernel(dependencies);
717
- const cachedJson = createCachedJson(dependencies);
718
- const middleware = kernel.globalMiddleware("web");
719
- const moduleRoutes = { ...seedRoutes };
929
+ const cachedJson = createApplicationCachedJson(dependencies);
930
+ const sources = [
931
+ { name: "seed routes", routes: seedRoutes, middleware: ["global", "web"] }
932
+ ];
720
933
  for (const module of modules) {
721
934
  if (!module.webRoutes) {
722
935
  continue;
723
936
  }
724
- Object.assign(moduleRoutes, module.webRoutes({
725
- dependencies,
726
- cachedJson,
727
- kernel
728
- }));
937
+ sources.push({
938
+ name: module.name,
939
+ routes: module.webRoutes({ dependencies, cachedJson, kernel }),
940
+ middleware: ["global", "web"]
941
+ });
729
942
  }
730
- return applyModuleRouteMiddleware(registerOpenApiRouteMap(moduleRoutes, ["global", "web"]), middleware);
943
+ const plan = compileRoutePlan(sources);
944
+ const routes = enterModuleRoutes(plan.routes, (callback) => kernel.composed(callback, "web"));
945
+ return publishRoutePlan(plan, routes);
731
946
  }
732
947
  // ../../src/bootstrap/cache/modelCacheTags.ts
733
- function cacheTagsForModelWrite(tableName, action) {
734
- const module = discoverModules().find((entry) => entry.tableName === tableName);
735
- const baseTags = module?.cacheTags ?? [`${tableName}s`];
736
- const isDelete = action === "deleted" || action === "force-deleted";
737
- const extraTags = isDelete ? module?.cacheDeleteExtraTags ?? [] : [];
738
- return [...new Set([...baseTags, ...extraTags])];
948
+ function cacheTagsForModelWrite(tableName, action, modules) {
949
+ const module = modules.find((entry) => entry.tableName === tableName);
950
+ const baseTags = module?.cacheTags ?? [tableName.endsWith("s") ? tableName : `${tableName}s`];
951
+ const extras = action === "deleted" || action === "force-deleted" ? module?.cacheDeleteExtraTags ?? [] : [];
952
+ return [...new Set([...baseTags, ...extras])];
739
953
  }
740
- function discoverModelTableNames() {
741
- return discoverModules().map((module) => module.tableName).filter((tableName) => tableName !== undefined);
954
+ function discoverModelTableNames(modules) {
955
+ return modules.map((module) => module.tableName).filter((name) => name !== undefined);
742
956
  }
743
957
  // ../../src/bootstrap/context.ts
744
958
  import { CORE_HTTP_CLEANUP_TOKEN as CORE_HTTP_CLEANUP_TOKEN2 } from "@getstrata/core/contracts/serviceTokens";
745
- import { clearActiveApplicationContext } from "@getstrata/core/runtime/applicationRegistry";
959
+ import { createApplication } from "@getstrata/core/runtime/application";
746
960
 
747
961
  // ../../src/bootstrap/contracts.ts
748
962
  import {
@@ -756,112 +970,110 @@ import {
756
970
  resolveService
757
971
  } from "@getstrata/core/contracts/di";
758
972
 
973
+ // ../../src/bootstrap/persistenceInvocation.ts
974
+ import { CORE_EXECUTION_OWNERSHIP_TOKEN } from "@getstrata/core/contracts/executionOwnership";
975
+ import { DATABASE_SESSION_TOKEN } from "@getstrata/core/database/tokens";
976
+ import { createScopedPolicy } from "@getstrata/core/tenant/scopedDatabasePolicy";
977
+ function createPersistenceInvocation(application, connection) {
978
+ if (!connection.trim())
979
+ throw new TypeError("A configured persistence connection is required.");
980
+ return (envelope, work) => application.run(envelope, (scope) => {
981
+ const database = scope.resolve(DATABASE_SESSION_TOKEN).connection(connection);
982
+ const policy = createScopedPolicy(scope.resolve(CORE_EXECUTION_OWNERSHIP_TOKEN), scope.context, database);
983
+ return work(Object.freeze({ database, policy }));
984
+ });
985
+ }
986
+
987
+ // ../../src/bootstrap/providers/index.ts
988
+ import { createStorageDriver as createStorageDriver2, resolveStorageConfig } from "@getstrata/core/storage/storage";
989
+
759
990
  // ../../src/bootstrap/providers/auth.ts
991
+ import { establishedAuthReader as establishedAuthReader3 } from "@getstrata/core/auth/authReader";
760
992
  import { BasicAuthGuard } from "@getstrata/core/auth/basicAuthGuard";
761
993
  import {
762
994
  AuthManager,
763
995
  CompositeGuard,
764
996
  DatabaseTokenGuard,
765
- GuestGuard
997
+ GuestGuard,
998
+ requireAuthCapability
766
999
  } from "@getstrata/core/auth/guard";
767
1000
  import { JwtGuard } from "@getstrata/core/auth/jwtGuard";
768
1001
  import { SessionGuard } from "@getstrata/core/auth/sessionGuard";
769
-
770
- // ../../src/config/auth.ts
771
- import { envFlagEnabled } from "@getstrata/core/runtime/appEnv";
772
- var authConfig = {
773
- allowDevHeaders: envFlagEnabled(process.env.AUTH_DEV_HEADERS),
774
- tokenDefaultAbilities: []
775
- };
776
-
777
- // ../../src/bootstrap/providers/auth.ts
778
1002
  var authProvider = {
779
1003
  name: "core.auth",
780
- register({ container, config }) {
781
- config.set("auth.allowDevHeaders", authConfig.allowDevHeaders);
782
- const apiGuard = new DatabaseTokenGuard(container);
783
- const sessionGuard = new SessionGuard(container);
784
- const jwtGuard = new JwtGuard(container);
785
- const basicGuard = new BasicAuthGuard(container);
786
- const guards = [apiGuard, jwtGuard, basicGuard, sessionGuard];
787
- if (authConfig.allowDevHeaders) {
788
- guards.push(new GuestGuard);
789
- }
790
- const auth = new AuthManager(new CompositeGuard(guards));
791
- auth.registerGuard("api", apiGuard);
792
- auth.registerGuard("access_token", apiGuard);
793
- auth.registerGuard("jwt", jwtGuard);
794
- auth.registerGuard("basic", basicGuard);
795
- auth.registerGuard("web", sessionGuard);
796
- auth.registerGuard("session", sessionGuard);
797
- container.set(CORE_AUTH_TOKEN, auth);
1004
+ register({ container }) {
1005
+ container.set(CORE_AUTH_TOKEN, establishedAuthReader3);
798
1006
  }
799
1007
  };
800
1008
  var auth_default = authProvider;
801
1009
 
802
- // ../../src/bootstrap/providers/cache.ts
803
- import { createCacheStore } from "@getstrata/core/cache/createCacheStore";
1010
+ // ../../src/bootstrap/providers/cacheProvider.ts
1011
+ import {
1012
+ createCacheStore,
1013
+ snapshotCacheStoreOptions
1014
+ } from "@getstrata/core/cache/createCacheStore";
804
1015
  import { CacheRepository } from "@getstrata/core/cache/repository";
805
- var cacheProvider = {
806
- name: "core.cache",
807
- register({ container, config, dependencies, onCleanup }) {
808
- container.singleton(CORE_CACHE_TOKEN, () => {
809
- const store = createCacheStore({
810
- driver: config.require(CACHE_DRIVER_CONFIG_KEY),
811
- ttlMs: config.require(CACHE_TTL_MS_CONFIG_KEY),
812
- maxEntries: config.require(CACHE_MAX_ENTRIES_CONFIG_KEY),
813
- redisUrl: config.get(REDIS_URL_CONFIG_KEY) || undefined
1016
+ function createCacheProvider(env) {
1017
+ const options = snapshotCacheStoreOptions({
1018
+ driver: env.CACHE_DRIVER ?? "array",
1019
+ ttlMs: Number(env.CACHE_TTL_MS ?? "3600000"),
1020
+ maxEntries: Number(env.CACHE_MAX_ENTRIES ?? "100"),
1021
+ redisUrl: env.REDIS_URL || undefined,
1022
+ namespace: `${env.APP_KEY_PREFIX?.trim() || "strata"}:cache:v3:`
1023
+ });
1024
+ return Object.freeze({
1025
+ name: "core.cache",
1026
+ register({
1027
+ container,
1028
+ dependencies,
1029
+ onCleanup
1030
+ }) {
1031
+ container.singleton(CORE_CACHE_TOKEN, () => {
1032
+ const cache = new CacheRepository(createCacheStore(options));
1033
+ onCleanup(() => cache.close());
1034
+ return cache;
814
1035
  });
815
- const cache = new CacheRepository(store);
816
- onCleanup(() => cache.close());
817
- return cache;
818
- });
819
- dependencies.cache = container.resolve(CORE_CACHE_TOKEN);
820
- }
821
- };
822
- var cache_default = cacheProvider;
1036
+ dependencies.cache = container.resolve(CORE_CACHE_TOKEN);
1037
+ }
1038
+ });
1039
+ }
823
1040
 
824
1041
  // ../../src/bootstrap/providers/config.ts
825
1042
  import { validateEnv } from "@getstrata/core/config/envSchema";
826
-
827
- // ../../src/config/app.ts
828
- var appConfig = {
829
- name: process.env.APP_NAME?.trim() || "Strata",
830
- env: process.env.APP_ENV ?? "local",
831
- debug: (process.env.APP_DEBUG ?? "false") === "true",
832
- url: process.env.APP_URL ?? "http://localhost:3000",
833
- apiPrefix: process.env.API_PREFIX ?? "/api/v1"
834
- };
1043
+ import { CORE_JSON_RESPONSE_POLICY_TOKEN as CORE_JSON_RESPONSE_POLICY_TOKEN2 } from "@getstrata/core/contracts/serviceTokens";
1044
+ import { resolveMaxBodyBytes } from "@getstrata/core/http/bodySizeLimitMiddleware";
1045
+ import { resolveCorsConfig as resolveCorsConfig2 } from "@getstrata/core/http/corsMiddleware";
1046
+ import { resolveMaxUploadBytes } from "@getstrata/core/http/uploads";
1047
+ import { envFlagEnabled, isProductionEnv } from "@getstrata/core/runtime/appEnv";
1048
+ import { parseFrontendMode } from "@getstrata/core/runtime/frontendMode";
1049
+ import { resolveDefaultTokenExpiryDays } from "@getstrata/core/security/tokenExpiry";
835
1050
 
836
1051
  // ../../src/core/queue/queueConfig.ts
837
- function resolveQueueConfig() {
838
- const driver = process.env.QUEUE_DRIVER;
839
- const maxAttempts = Number(process.env.QUEUE_MAX_ATTEMPTS ?? "3");
840
- const backoffMs = Number(process.env.QUEUE_BACKOFF_MS ?? "1000");
841
- return {
842
- driver: driver === "redis" || driver === "async" || driver === "sync" ? driver : "sync",
843
- maxAttempts: Number.isFinite(maxAttempts) && maxAttempts > 0 ? maxAttempts : 3,
844
- backoffMs: Number.isFinite(backoffMs) && backoffMs >= 0 ? backoffMs : 1000
845
- };
1052
+ function snapshotQueueRetryPolicy(policy) {
1053
+ const { maxAttempts, backoffMs } = policy;
1054
+ if (!Number.isSafeInteger(maxAttempts) || maxAttempts < 1)
1055
+ throw new TypeError("QUEUE_MAX_ATTEMPTS must be a positive safe integer.");
1056
+ if (!Number.isSafeInteger(backoffMs) || backoffMs < 0 || backoffMs > 2147483647)
1057
+ throw new TypeError("QUEUE_BACKOFF_MS must be a non-negative integer within the timer range.");
1058
+ return Object.freeze({ maxAttempts, backoffMs });
1059
+ }
1060
+ function resolveQueueConfig(env = process.env) {
1061
+ const driver = env.QUEUE_DRIVER ?? "sync";
1062
+ if (!["sync", "async", "redis"].includes(driver))
1063
+ throw new TypeError("Unknown queue driver.");
1064
+ const policy = snapshotQueueRetryPolicy({
1065
+ maxAttempts: Number(env.QUEUE_MAX_ATTEMPTS ?? "3"),
1066
+ backoffMs: Number(env.QUEUE_BACKOFF_MS ?? "1000")
1067
+ });
1068
+ return Object.freeze({ driver, ...policy });
846
1069
  }
847
- var queueConfig = {
848
- get driver() {
849
- return resolveQueueConfig().driver;
850
- },
851
- get maxAttempts() {
852
- return resolveQueueConfig().maxAttempts;
853
- },
854
- get backoffMs() {
855
- return resolveQueueConfig().backoffMs;
856
- }
857
- };
858
1070
  // ../../src/bootstrap/env.ts
859
1071
  import { defineEnvSchema } from "@getstrata/core/config/envSchema";
860
1072
  import { DEFAULT_SPA_PREFIX, FRONTEND_MODE_PATTERN } from "@getstrata/core/runtime/frontendMode";
861
1073
  var appEnvSchema = defineEnvSchema({
862
1074
  DATABASE_URL: {
863
1075
  required: true,
864
- pattern: /^(postgres(ql)?|mysql|sqlite):\/\//i
1076
+ pattern: /^(?:(?:postgres(?:ql)?|mysql):\/\/\S+|sqlite:(?:\/\/)?\S+)$/i
865
1077
  },
866
1078
  PORT: {
867
1079
  integer: true,
@@ -969,194 +1181,72 @@ var appEnvSchema = defineEnvSchema({
969
1181
  });
970
1182
 
971
1183
  // ../../src/bootstrap/providers/config.ts
972
- function parseInteger(value, envName, minimum) {
973
- const parsed = Number.parseInt(value, 10);
974
- if (!Number.isInteger(parsed) || parsed < minimum) {
975
- const comparison = minimum === 0 ? "a non-negative" : `an integer >= ${minimum}`;
976
- throw new Error(`${envName} must be ${comparison} value.`);
977
- }
978
- return parsed;
979
- }
980
- var configProvider = {
981
- name: "core.config",
982
- register({ container, config }) {
983
- const env = validateEnv(appEnvSchema);
984
- container.set(CORE_CONFIG_TOKEN, config);
985
- if (process.env.CSRF_TARGET_ORIGIN !== undefined)
986
- config.set(CSRF_TARGET_ORIGIN_CONFIG_KEY, process.env.CSRF_TARGET_ORIGIN);
987
- config.set(DATABASE_URL_CONFIG_KEY, env.DATABASE_URL);
988
- config.set(APP_PORT_CONFIG_KEY, parseInteger(env.PORT ?? String(DEFAULT_APP_PORT), "PORT", 1));
989
- config.set(CACHE_TTL_MS_CONFIG_KEY, parseInteger(env.CACHE_TTL_MS ?? String(DEFAULT_CACHE_TTL_MS), "CACHE_TTL_MS", 0));
990
- config.set(CACHE_MAX_ENTRIES_CONFIG_KEY, parseInteger(env.CACHE_MAX_ENTRIES ?? String(DEFAULT_CACHE_MAX_ENTRIES), "CACHE_MAX_ENTRIES", 1));
991
- config.set(CACHE_DRIVER_CONFIG_KEY, env.CACHE_DRIVER ?? DEFAULT_CACHE_DRIVER);
992
- config.set(REDIS_URL_CONFIG_KEY, env.REDIS_URL ?? "");
993
- config.set("app.env", appConfig.env);
994
- config.set("app.debug", appConfig.debug);
995
- config.set("app.url", appConfig.url);
996
- config.set("app.apiPrefix", appConfig.apiPrefix);
997
- config.set("auth.allowDevHeaders", authConfig.allowDevHeaders);
998
- config.set("queue.driver", queueConfig.driver);
999
- config.set("queue.maxAttempts", queueConfig.maxAttempts);
1000
- config.set("queue.backoffMs", queueConfig.backoffMs);
1001
- }
1002
- };
1003
- var config_default = configProvider;
1004
-
1005
- // ../../src/bootstrap/providers/events.ts
1006
- import { eventBus } from "@getstrata/core/events";
1007
- var eventsProvider = {
1008
- name: "core.events",
1009
- register({ container }) {
1010
- container.set(CORE_EVENT_BUS_TOKEN, eventBus);
1011
- }
1012
- };
1013
- var events_default = eventsProvider;
1014
-
1015
- // ../../src/bootstrap/discoverListeners.ts
1016
- import { join as join3, resolve as resolve2 } from "path";
1017
- var KEY2 = Symbol.for("@getstrata/discoverListenersState");
1018
- function state2() {
1019
- const globals = globalThis;
1020
- globals[KEY2] ??= { loads: new Map };
1021
- return globals[KEY2];
1022
- }
1023
- async function load2(options) {
1024
- const listeners = new Set;
1025
- const add = (value, location) => {
1026
- if (typeof value !== "function")
1027
- throw new TypeError(`Invalid listener registrar at ${location}: expected a default function.`);
1028
- listeners.add(value);
1029
- };
1030
- if (options.manifest)
1031
- for (const [index, value] of options.manifest.entries())
1032
- add(value, `listener manifest[${index}]`);
1033
- else
1034
- for (const file of await infrastructureFiles(options.directory ?? join3(process.cwd(), "src", "listeners"), options.exclude)) {
1035
- const exports = await importInfrastructure(file);
1036
- const value = exports.default;
1037
- add(value && typeof value === "object" && "default" in value ? value.default : value, file);
1038
- }
1039
- return [...listeners];
1040
- }
1041
- function discoverListeners(options = {}) {
1042
- const cache = state2().loads;
1043
- const key = options.manifest ?? JSON.stringify([
1044
- resolve2(options.directory ?? join3(process.cwd(), "src", "listeners")),
1045
- [...options.exclude ?? []].sort()
1046
- ]);
1047
- const existing = cache.get(key);
1048
- if (existing)
1049
- return existing;
1050
- const pending = load2(options).catch((error) => {
1051
- if (cache.get(key) === pending)
1052
- cache.delete(key);
1053
- throw error;
1184
+ function resolveHttpResponsePolicy(source) {
1185
+ const cors = Object.freeze({
1186
+ allowedOrigins: Object.freeze((source.CORS_ALLOWED_ORIGINS ?? (source.APP_URL?.trim() || "http://localhost:3000").replace(/\/$/, "")).split(",").map((origin) => origin.trim()).filter(Boolean)),
1187
+ additionalAllowedHeaders: Object.freeze(source.CORS_ADDITIONAL_ALLOWED_HEADERS?.trim() ? source.CORS_ADDITIONAL_ALLOWED_HEADERS.split(",").map((name) => name.trim()) : [])
1188
+ });
1189
+ resolveCorsConfig2(cors);
1190
+ const maxAttempts = Number(source.RATE_LIMIT_PER_MINUTE ?? "120");
1191
+ return Object.freeze({
1192
+ cors,
1193
+ securityHeaders: Object.freeze({
1194
+ frontendMode: parseFrontendMode(source.FRONTEND_MODE),
1195
+ production: isProductionEnv(source)
1196
+ }),
1197
+ maxBodyBytes: resolveMaxBodyBytes(source.MAX_REQUEST_BODY_BYTES),
1198
+ rateLimitPerMinute: Number.isFinite(maxAttempts) ? maxAttempts : 120,
1199
+ namespace: source.APP_KEY_PREFIX?.trim() || "strata",
1200
+ trustForwardedFor: source.TRUST_FORWARDED_FOR === "true",
1201
+ loginRateLimit: Object.freeze(resolveLoginRateLimit({ APP_ENV: "local", ...source })),
1202
+ registerRateLimit: Object.freeze(resolveRegisterRateLimit({ APP_ENV: "local", ...source }))
1054
1203
  });
1055
- cache.set(key, pending);
1056
- return pending;
1057
- }
1058
-
1059
- // ../../src/bootstrap/listeners/invalidateCacheOnModelWrite.ts
1060
- import { eventBus as eventBus2, modelEventName } from "@getstrata/core/events";
1061
- import { InvalidateCacheTagsJob } from "@getstrata/core/jobs/invalidateCacheTagsJob";
1062
- import { createTrackedJob } from "@getstrata/core/queue/createAppQueue";
1063
- var MODEL_WRITE_ACTIONS = ["created", "updated", "deleted", "restored", "force-deleted"];
1064
- var CACHE_EVENT = "strata.cache.invalidate-tags";
1065
- var STATE_KEY = Symbol.for("@getstrata/modelCacheInvalidationRegistrations");
1066
- function registrations() {
1067
- const global = globalThis;
1068
- global[STATE_KEY] ??= new WeakMap;
1069
- return global[STATE_KEY];
1070
- }
1071
- function requireCacheTags(value) {
1072
- if (!Array.isArray(value) || !value.length || value.length > 128 || !value.every((tag) => typeof tag === "string" && tag.length > 0 && tag.length <= 256))
1073
- throw new Error("Invalid durable cache invalidation payload.");
1074
- return value;
1075
1204
  }
1076
- function registerInvalidateCacheOnModelWriteListeners(bus = eventBus2, options = {}) {
1077
- if (options.outbox && !options.outbox.hasListener("strata.cache.invalidate-tags.v1", CACHE_EVENT))
1078
- throw new Error("The application outbox must include createModelCacheInvalidationListener().");
1079
- const writes = discoverModelTableNames().flatMap((tableName) => MODEL_WRITE_ACTIONS.map((action) => ({
1080
- tableName,
1081
- action,
1082
- tags: cacheTagsForModelWrite(tableName, action)
1083
- })));
1084
- if (options.outbox) {
1085
- for (const write of writes)
1086
- if (write.tags.length)
1087
- requireCacheTags(write.tags);
1088
- }
1089
- const state = registrations();
1090
- const previous = state.get(bus);
1091
- if (previous?.durable && !options.outbox)
1092
- return () => {};
1093
- previous?.suspend();
1094
- const unsubscribe = [];
1095
- const subscribe = [];
1096
- const registration = {
1097
- durable: !!options.outbox,
1098
- suspend() {
1099
- for (const stop of unsubscribe.splice(0))
1100
- stop();
1101
- },
1102
- resume() {
1103
- for (const start of subscribe)
1104
- unsubscribe.push(start());
1105
- state.set(bus, registration);
1106
- },
1107
- dispose() {
1108
- if (state.get(bus) !== registration)
1109
- return;
1110
- registration.suspend();
1111
- if (previous)
1112
- previous.resume();
1113
- else
1114
- state.delete(bus);
1115
- }
1116
- };
1117
- for (const { tableName, action, tags: durableTags } of writes) {
1118
- const event = modelEventName(tableName, action);
1119
- if (options.outbox) {
1120
- if (!durableTags.length)
1121
- continue;
1122
- const outbox = options.outbox;
1123
- subscribe.push(() => bus.listenTransactional(event, async () => {
1124
- await outbox.publish(CACHE_EVENT, { tags: durableTags });
1125
- }));
1126
- } else {
1127
- subscribe.push(() => bus.listen(event, async () => {
1128
- const tags = cacheTagsForModelWrite(tableName, action);
1129
- if (!tags.length)
1130
- return;
1131
- let cache;
1132
- let queue;
1133
- try {
1134
- cache = resolveApplicationCache();
1135
- queue = resolveApplicationQueue();
1136
- } catch {
1137
- return;
1138
- }
1139
- const job = createTrackedJob("cache.invalidate-tags", new InvalidateCacheTagsJob(cache));
1140
- await queue.dispatch(job, { tags });
1141
- }));
1205
+ function createConfigProvider(input) {
1206
+ const source = Object.freeze({ ...input });
1207
+ const env = validateEnv(appEnvSchema, source);
1208
+ const queue = resolveQueueConfig(env);
1209
+ const values = Object.freeze({
1210
+ [DATABASE_URL_CONFIG_KEY]: env.DATABASE_URL,
1211
+ [APP_PORT_CONFIG_KEY]: Number(env.PORT),
1212
+ [CACHE_TTL_MS_CONFIG_KEY]: Number(env.CACHE_TTL_MS),
1213
+ [CACHE_MAX_ENTRIES_CONFIG_KEY]: Number(env.CACHE_MAX_ENTRIES),
1214
+ [CACHE_DRIVER_CONFIG_KEY]: env.CACHE_DRIVER,
1215
+ [REDIS_URL_CONFIG_KEY]: env.REDIS_URL,
1216
+ "http.responsePolicy": resolveHttpResponsePolicy({ ...source, APP_URL: env.APP_URL }),
1217
+ "http.features": Object.freeze({
1218
+ emailVerificationRequired: source.FEATURE_EMAIL_VERIFICATION === "true",
1219
+ viewsEnabled: ["server-htmx", "hybrid"].includes(source.FRONTEND_MODE ?? "api"),
1220
+ publicReadsEnabled: source.FEATURE_PUBLIC_READS === "true",
1221
+ etagEnabled: source.FEATURE_ETAG !== "false"
1222
+ }),
1223
+ "http.uploadPolicy": Object.freeze({
1224
+ maxBytes: resolveMaxUploadBytes(source.MAX_UPLOAD_BYTES?.trim() ?? source.MAX_REQUEST_BODY_BYTES?.trim()),
1225
+ allowUnknownMime: envFlagEnabled(source.UPLOAD_ALLOW_UNKNOWN_MIME)
1226
+ }),
1227
+ "auth.defaultTokenExpiryDays": resolveDefaultTokenExpiryDays(source.API_TOKEN_DEFAULT_EXPIRY_DAYS),
1228
+ "app.name": source.APP_NAME?.trim() || "Strata",
1229
+ "app.env": env.APP_ENV,
1230
+ "app.debug": source.APP_DEBUG === "true",
1231
+ "app.url": env.APP_URL,
1232
+ "app.apiPrefix": env.API_PREFIX,
1233
+ "auth.allowDevHeaders": envFlagEnabled(env.AUTH_DEV_HEADERS),
1234
+ "queue.driver": queue.driver,
1235
+ "queue.maxAttempts": queue.maxAttempts,
1236
+ "queue.backoffMs": queue.backoffMs,
1237
+ ...source.CSRF_TARGET_ORIGIN !== undefined ? { [CSRF_TARGET_ORIGIN_CONFIG_KEY]: source.CSRF_TARGET_ORIGIN } : {}
1238
+ });
1239
+ return Object.freeze({
1240
+ name: "core.config",
1241
+ register({ container, config }) {
1242
+ container.set(CORE_CONFIG_TOKEN, config);
1243
+ container.set(CORE_JSON_RESPONSE_POLICY_TOKEN2, Object.freeze({ etagEnabled: source.FEATURE_ETAG !== "false" }));
1244
+ for (const [key, value] of Object.entries(values))
1245
+ config.set(key, value);
1142
1246
  }
1143
- }
1144
- registration.resume();
1145
- return registration.dispose;
1247
+ });
1146
1248
  }
1147
1249
 
1148
- // ../../src/bootstrap/providers/listeners.ts
1149
- var listenersProvider = {
1150
- name: "core.listeners",
1151
- async boot({ onCleanup }) {
1152
- onCleanup(registerInvalidateCacheOnModelWriteListeners());
1153
- for (const registerListener of await discoverListeners()) {
1154
- await registerListener();
1155
- }
1156
- }
1157
- };
1158
- var listeners_default = listenersProvider;
1159
-
1160
1250
  // ../../src/bootstrap/providers/policy.ts
1161
1251
  import { PolicyGate } from "@getstrata/core/auth/policy";
1162
1252
  var policyProvider = {
@@ -1164,31 +1254,87 @@ var policyProvider = {
1164
1254
  register({ container }) {
1165
1255
  container.set(CORE_POLICY_GATE_TOKEN, new PolicyGate);
1166
1256
  }
1167
- };
1168
- var policy_default = policyProvider;
1169
-
1170
- // ../../src/bootstrap/providers/queue.ts
1171
- import {
1172
- createAppQueue,
1173
- createFailedJobService,
1174
- FAILED_JOB_SERVICE_TOKEN
1175
- } from "@getstrata/core/queue/createAppQueue";
1257
+ };
1258
+ var policy_default = policyProvider;
1259
+
1260
+ // ../../src/bootstrap/providers/queue.ts
1261
+ import { createAuditExporter } from "@getstrata/core/audit/exportAuditLogs";
1262
+ import {
1263
+ createAppQueue,
1264
+ createSystemQueueServices,
1265
+ FAILED_JOB_SERVICE_TOKEN
1266
+ } from "@getstrata/core/queue/createAppQueue";
1267
+ import { JobRegistry, QUEUE_JOB_REGISTRY_TOKEN } from "@getstrata/core/queue/jobRegistry";
1268
+ import { resolveQueueConfig as resolveQueueConfig2, resolveQueueRuntimeConfig } from "@getstrata/core/queue/queueConfig";
1269
+
1270
+ // ../../src/bootstrap/discoverJobs.ts
1271
+ import { join as join2, resolve } from "path";
1272
+ import { Job } from "@getstrata/core/queue";
1273
+
1274
+ // ../../src/bootstrap/infrastructureDiscovery.ts
1275
+ import { readdir } from "fs/promises";
1276
+ import { join, relative } from "path";
1277
+ import { pathToFileURL } from "url";
1278
+ async function infrastructureFiles(directory, exclude = []) {
1279
+ const excluded = new Set([
1280
+ "index.ts",
1281
+ "index.js",
1282
+ "index.mts",
1283
+ "index.mjs",
1284
+ "register.ts",
1285
+ "register.js",
1286
+ "register.mts",
1287
+ "register.mjs",
1288
+ ...exclude
1289
+ ]);
1290
+ const files = [];
1291
+ async function visit(path) {
1292
+ const entries = await readdir(path, { withFileTypes: true });
1293
+ entries.sort((a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0);
1294
+ for (const entry of entries) {
1295
+ const file = join(path, entry.name);
1296
+ const key = relative(directory, file).replaceAll("\\", "/");
1297
+ if (excluded.has(entry.name) || excluded.has(key))
1298
+ continue;
1299
+ if (entry.isDirectory())
1300
+ await visit(file);
1301
+ else if (entry.isFile() && /\.(ts|js|mts|mjs)$/.test(entry.name) && !/\.(d|test|spec)\.[cm]?[jt]s$/.test(entry.name))
1302
+ files.push(file);
1303
+ }
1304
+ }
1305
+ try {
1306
+ await visit(directory);
1307
+ } catch (error) {
1308
+ if (error.code !== "ENOENT")
1309
+ throw error;
1310
+ if (error.path !== directory)
1311
+ throw error;
1312
+ }
1313
+ return files;
1314
+ }
1315
+ async function importInfrastructure(file) {
1316
+ try {
1317
+ return await import(pathToFileURL(file).href);
1318
+ } catch (error) {
1319
+ throw new Error(`Cannot load infrastructure module ${file}`, { cause: error });
1320
+ }
1321
+ }
1176
1322
 
1177
1323
  // ../../src/bootstrap/discoverJobs.ts
1178
- import { join as join4, resolve as resolve3 } from "path";
1179
- import { Job } from "@getstrata/core/queue";
1180
- import { jobRegistry } from "@getstrata/core/queue/jobRegistry";
1181
- var KEY3 = Symbol.for("@getstrata/discoverJobsState");
1182
- function state3() {
1183
- const globals = globalThis;
1184
- globals[KEY3] ??= { loads: new Map, registered: new Map };
1185
- return globals[KEY3];
1324
+ var states = new WeakMap;
1325
+ function state(registry) {
1326
+ let value = states.get(registry);
1327
+ if (!value) {
1328
+ value = { loads: new Map, registered: new Map };
1329
+ states.set(registry, value);
1330
+ }
1331
+ return value;
1186
1332
  }
1187
1333
  function validateClass(value, location) {
1188
1334
  if (typeof value !== "function" || typeof value.jobName !== "string" || !value.jobName.trim() || !(value.prototype instanceof Job) && typeof value.prototype?.handle !== "function")
1189
1335
  throw new TypeError(`Invalid job at ${location}: expected a class with nonempty static jobName and handle().`);
1190
1336
  }
1191
- async function load3(options, current) {
1337
+ async function load(registry, options, current) {
1192
1338
  const jobs = new Map;
1193
1339
  const add = (name, identity, create, location) => {
1194
1340
  const previous = jobs.get(name);
@@ -1210,7 +1356,7 @@ async function load3(options, current) {
1210
1356
  }
1211
1357
  }
1212
1358
  } else {
1213
- for (const file of await infrastructureFiles(options.directory ?? join4(process.cwd(), "src", "jobs"), options.exclude)) {
1359
+ for (const file of await infrastructureFiles(options.directory ?? join2(process.cwd(), "src", "jobs"), options.exclude)) {
1214
1360
  const exports = await importInfrastructure(file);
1215
1361
  const defaultValue = exports.default;
1216
1362
  const legacy = defaultValue && typeof defaultValue === "object" && "default" in defaultValue ? defaultValue.default : defaultValue;
@@ -1233,31 +1379,31 @@ async function load3(options, current) {
1233
1379
  }
1234
1380
  if (!current())
1235
1381
  return [...jobs.keys()];
1236
- const registered = state3().registered;
1382
+ const registered = state(registry).registered;
1237
1383
  for (const [name, entry] of jobs) {
1238
1384
  const previous = registered.get(name);
1239
1385
  if (previous && previous.identity !== entry.identity)
1240
1386
  throw new Error(`Duplicate discovered job "${name}" at ${entry.location}; first declared at ${previous.location}.`);
1241
1387
  }
1242
- const existing = new Set(jobRegistry.names());
1388
+ const existing = new Set(registry.names());
1243
1389
  for (const [name, entry] of jobs) {
1244
1390
  if (!existing.has(name)) {
1245
- jobRegistry.register(name, entry.create);
1391
+ registry.register(name, entry.create);
1246
1392
  registered.set(name, entry);
1247
1393
  }
1248
1394
  }
1249
1395
  return [...jobs.keys()];
1250
1396
  }
1251
- function discoverJobs(options = {}) {
1252
- const cache = state3().loads;
1397
+ function discoverJobs(registry, options = {}) {
1398
+ const cache = state(registry).loads;
1253
1399
  const key = options.manifest ?? JSON.stringify([
1254
- resolve3(options.directory ?? join4(process.cwd(), "src", "jobs")),
1400
+ resolve(options.directory ?? join2(process.cwd(), "src", "jobs")),
1255
1401
  [...options.exclude ?? []].sort()
1256
1402
  ]);
1257
1403
  const existing = cache.get(key);
1258
1404
  if (existing)
1259
1405
  return existing;
1260
- const pending = load3(options, () => state3().loads === cache).catch((error) => {
1406
+ const pending = load(registry, options, () => state(registry).loads === cache).catch((error) => {
1261
1407
  if (cache.get(key) === pending)
1262
1408
  cache.delete(key);
1263
1409
  throw error;
@@ -1265,299 +1411,355 @@ function discoverJobs(options = {}) {
1265
1411
  cache.set(key, pending);
1266
1412
  return pending;
1267
1413
  }
1268
- function resetDiscoverJobsForTests() {
1269
- state3().loads = new Map;
1270
- state3().registered = new Map;
1414
+ function resetDiscoverJobsForTests(registry) {
1415
+ state(registry).loads = new Map;
1416
+ state(registry).registered = new Map;
1271
1417
  }
1272
1418
 
1273
1419
  // ../../src/bootstrap/queue/defaultJobs.ts
1274
1420
  import { ExportAuditLogsJob } from "@getstrata/core/jobs/exportAuditLogsJob";
1275
- import { InvalidateCacheTagsJob as InvalidateCacheTagsJob2 } from "@getstrata/core/jobs/invalidateCacheTagsJob";
1276
- import { jobRegistry as jobRegistry2 } from "@getstrata/core/queue/jobRegistry";
1277
- import { resolveApplicationCache as resolveApplicationCache2 } from "@getstrata/core/runtime/applicationRegistry";
1278
- function registerDefaultJobs() {
1279
- jobRegistry2.register("cache.invalidate-tags", () => {
1280
- return new InvalidateCacheTagsJob2(resolveApplicationCache2());
1421
+ import { InvalidateCacheTagsJob } from "@getstrata/core/jobs/invalidateCacheTagsJob";
1422
+ var SYSTEM_JOB_NAMES = Object.freeze([
1423
+ InvalidateCacheTagsJob.jobName,
1424
+ ExportAuditLogsJob.jobName
1425
+ ]);
1426
+ function registerDefaultJobs(registry) {
1427
+ registry.register(InvalidateCacheTagsJob.jobName, () => {
1428
+ return new InvalidateCacheTagsJob;
1281
1429
  });
1282
- jobRegistry2.register("audit.export", () => new ExportAuditLogsJob);
1430
+ registry.register(ExportAuditLogsJob.jobName, () => new ExportAuditLogsJob);
1283
1431
  }
1284
1432
 
1285
1433
  // ../../src/bootstrap/providers/queue.ts
1286
- var queueProvider = {
1287
- name: "core.queue",
1288
- async register({ container, config, onCleanup }) {
1289
- const configuredDriver = process.env.QUEUE_DRIVER ?? DEFAULT_QUEUE_DRIVER;
1290
- const driver = configuredDriver === "async" || configuredDriver === "redis" || configuredDriver === "sync" ? configuredDriver : DEFAULT_QUEUE_DRIVER;
1291
- config.set("queue.driver", driver);
1292
- const failedJobs = createFailedJobService();
1293
- container.set(FAILED_JOB_SERVICE_TOKEN, failedJobs);
1294
- registerDefaultJobs();
1295
- await discoverJobs();
1296
- const queue = createAppQueue(driver, config.get(REDIS_URL_CONFIG_KEY) ?? process.env.REDIS_URL, failedJobs);
1297
- onCleanup(() => queue.close?.(), driver === "async" ? "drain" : "close");
1298
- container.set(CORE_QUEUE_TOKEN, queue);
1299
- }
1300
- };
1301
- var queue_default = queueProvider;
1434
+ function createQueueProvider(env = process.env, handoff) {
1435
+ const environment = Object.freeze({ ...env });
1436
+ const retryPolicy = resolveQueueConfig2(environment);
1437
+ const runtime = resolveQueueRuntimeConfig(environment);
1438
+ return {
1439
+ name: "core.queue",
1440
+ async register({ container, config, onCleanup, invoke }) {
1441
+ const configuredDriver = environment.QUEUE_DRIVER ?? DEFAULT_QUEUE_DRIVER;
1442
+ const driver = configuredDriver === "async" || configuredDriver === "redis" || configuredDriver === "sync" ? configuredDriver : DEFAULT_QUEUE_DRIVER;
1443
+ config.set("queue.driver", driver);
1444
+ const failedJobs = createSystemQueueServices(invoke, {
1445
+ cache: container.resolve(CORE_CACHE_TOKEN),
1446
+ auditExport: createAuditExporter({
1447
+ environment,
1448
+ runSql: (work) => invoke({ kind: "command", actor: { kind: "system", policy: "audit.export" } }, ({ database, policy }) => environment.TENANCY_DRIVER === "rls" ? policy.run(database, { kind: "bypass" }, work) : database.transaction(work))
1449
+ })
1450
+ }, handoff, SYSTEM_JOB_NAMES);
1451
+ container.set(FAILED_JOB_SERVICE_TOKEN, failedJobs);
1452
+ const registry = new JobRegistry;
1453
+ registerDefaultJobs(registry);
1454
+ await discoverJobs(registry);
1455
+ const queue = createAppQueue(driver, config.get(REDIS_URL_CONFIG_KEY) ?? environment.REDIS_URL, failedJobs, registry, retryPolicy, runtime);
1456
+ onCleanup(() => queue.close?.(), driver === "async" ? "drain" : "close");
1457
+ container.set(CORE_QUEUE_TOKEN, queue);
1458
+ container.set(QUEUE_JOB_REGISTRY_TOKEN, registry);
1459
+ }
1460
+ };
1461
+ }
1302
1462
 
1303
1463
  // ../../src/bootstrap/providers/storage.ts
1304
- import { createStorageDriver, StorageManager } from "@getstrata/core/storage/storage";
1305
- var storageProvider = {
1306
- name: "core.storage",
1307
- register({ dependencies }) {
1308
- dependencies.storage = new StorageManager(createStorageDriver());
1309
- }
1310
- };
1311
- var storage_default = storageProvider;
1464
+ import { service } from "@getstrata/core/contracts/services";
1465
+ import {
1466
+ CORE_STORAGE_TOKEN,
1467
+ createStorageDriver,
1468
+ StorageManager,
1469
+ snapshotStorageConfig
1470
+ } from "@getstrata/core/storage/storage";
1471
+ function createStorageBindings(config) {
1472
+ let create;
1473
+ if (config.driver === "custom") {
1474
+ const driver = config.storage;
1475
+ assertStorageDriver(driver);
1476
+ create = () => driver;
1477
+ } else {
1478
+ const snapshot = snapshotStorageConfig(config);
1479
+ create = () => createStorageDriver(snapshot);
1480
+ }
1481
+ return Object.freeze([
1482
+ service(CORE_STORAGE_TOKEN, {
1483
+ lifetime: "application",
1484
+ dependencies: [],
1485
+ create: () => new StorageManager(create())
1486
+ })
1487
+ ]);
1488
+ }
1489
+ function assertStorageDriver(driver) {
1490
+ if (!driver || [driver.put, driver.get, driver.delete].some((method) => typeof method !== "function"))
1491
+ throw new TypeError("Storage requires put, get, and delete capabilities.");
1492
+ }
1493
+ function createStorageProvider(driver) {
1494
+ assertStorageDriver(driver);
1495
+ return Object.freeze({
1496
+ name: "core.storage",
1497
+ register({ dependencies }) {
1498
+ dependencies.storage = new StorageManager(driver);
1499
+ }
1500
+ });
1501
+ }
1312
1502
 
1313
1503
  // ../../src/bootstrap/providers/tracing.ts
1314
- import { acquireTracingRuntime } from "@getstrata/core/tracing/tracingMiddleware";
1315
- var tracingProvider = {
1316
- name: "core.tracing",
1317
- register({ onCleanup }) {
1318
- const ownership = acquireTracingRuntime();
1319
- onCleanup(() => ownership.flush(), "flush");
1320
- onCleanup(() => ownership.release(), "close");
1321
- }
1322
- };
1323
- var tracing_default = tracingProvider;
1504
+ import { CORE_TRACING_RUNTIME_TOKEN as CORE_TRACING_RUNTIME_TOKEN2 } from "@getstrata/core/contracts/serviceTokens";
1505
+ import {
1506
+ captureTracingOptions,
1507
+ createTracingRuntime
1508
+ } from "@getstrata/core/tracing/tracingMiddleware";
1509
+ function createTracingProvider(options = {}) {
1510
+ const configured = captureTracingOptions(options);
1511
+ let registered = false;
1512
+ return {
1513
+ name: "core.tracing",
1514
+ register({ container, onCleanup }) {
1515
+ if (registered)
1516
+ throw new Error("A tracing provider belongs to one application context; create a new provider for each context.");
1517
+ registered = true;
1518
+ const runtime = createTracingRuntime(configured);
1519
+ onCleanup(() => runtime.shutdown(), "close");
1520
+ onCleanup(() => runtime.forceFlush(), "flush");
1521
+ container.set(CORE_TRACING_RUNTIME_TOKEN2, runtime);
1522
+ }
1523
+ };
1524
+ }
1324
1525
 
1325
1526
  // ../../src/bootstrap/providers/view.ts
1326
- import { currentRequestMeta } from "@getstrata/core/http/requestMetaContext";
1327
- import { appDisplayName } from "@getstrata/core/runtime/appKeyPrefix";
1328
- import { isViewsEnabled as isViewsEnabled2 } from "@getstrata/core/runtime/frontendMode";
1527
+ import { resolve as resolve2 } from "path";
1528
+ import { csrfTokenOptionsFromEnvironment } from "@getstrata/core/http/csrfToken";
1529
+ import { flashSessionOptionsFromEnvironment } from "@getstrata/core/http/flashSession";
1530
+ import { isViewsMode, parseFrontendMode as parseFrontendMode2 } from "@getstrata/core/runtime/frontendMode";
1329
1531
  import {
1330
- CORE_VIEW_RENDERER_TOKEN,
1331
- configureWebErrorView,
1332
- configureWebLayoutData,
1532
+ createWebErrorView,
1333
1533
  createWebLayoutDataResolver,
1334
- DEFAULT_VIEWS_DIRECTORY,
1335
1534
  EtaViewEngine,
1336
1535
  errorTemplateName,
1337
- resolveWebLayoutData,
1338
1536
  ViewRenderer
1339
1537
  } from "@getstrata/core/view";
1340
- var CORE_VIEW_TOKEN = "core.view";
1538
+ import {
1539
+ CORE_VIEW_RENDERER_TOKEN,
1540
+ CORE_VIEW_TOKEN,
1541
+ CORE_WEB_ERROR_VIEW_TOKEN as CORE_WEB_ERROR_VIEW_TOKEN2
1542
+ } from "@getstrata/core/view/tokens";
1341
1543
  var VIEW_DIRECTORY_CONFIG_KEY = "view.directory";
1342
- var viewProvider = {
1343
- name: "view",
1344
- register({ container, config }) {
1345
- if (!isViewsEnabled2()) {
1346
- return;
1347
- }
1348
- const viewsDirectory = process.env.VIEW_DIRECTORY?.trim() || DEFAULT_VIEWS_DIRECTORY;
1349
- config.set(VIEW_DIRECTORY_CONFIG_KEY, viewsDirectory);
1350
- const engine = new EtaViewEngine(viewsDirectory, (request) => resolveWebLayoutData(container, request ?? currentRequestMeta().request));
1351
- container.set(CORE_VIEW_TOKEN, engine);
1352
- container.set(CORE_VIEW_RENDERER_TOKEN, new ViewRenderer(engine));
1353
- configureWebLayoutData({
1354
- extra: async () => ({
1355
- appName: appDisplayName(),
1356
- currentOrganization: null,
1357
- organizations: []
1358
- })
1359
- });
1360
- configureWebErrorView({
1361
- render: async (input) => engine.render(errorTemplateName(input.status), {
1362
- title: input.title,
1363
- message: input.message,
1364
- errors: input.errors
1365
- })
1366
- });
1367
- }
1368
- };
1544
+ function createViewProvider(options = {}) {
1545
+ const env = { ...options.env ?? process.env };
1546
+ const enabled = options.enabled ?? isViewsMode(parseFrontendMode2(env.FRONTEND_MODE));
1547
+ const directory = resolve2(options.rootDir ?? process.cwd(), options.directory ?? (env.VIEW_DIRECTORY?.trim() || "resources/views"));
1548
+ const layout = options.layout;
1549
+ const appName = env.APP_NAME?.trim() || "Strata";
1550
+ const extra = options.data?.extra;
1551
+ const defaults = { appName, currentOrganization: null, organizations: [] };
1552
+ const data = {
1553
+ ...options.data,
1554
+ csrf: options.data?.csrf ? { ...options.data.csrf } : enabled ? csrfTokenOptionsFromEnvironment(env) : undefined,
1555
+ flash: options.data?.flash ? { ...options.data.flash } : enabled ? flashSessionOptionsFromEnvironment(env) : undefined,
1556
+ extra: typeof extra === "function" ? async (user) => ({ ...defaults, ...await extra(user) }) : { ...defaults, ...extra }
1557
+ };
1558
+ const customErrorRender = options.error?.render;
1559
+ return {
1560
+ name: "view",
1561
+ register({ container, config }) {
1562
+ if (!enabled)
1563
+ return;
1564
+ config.set(VIEW_DIRECTORY_CONFIG_KEY, directory);
1565
+ const engine = new EtaViewEngine(directory, createWebLayoutDataResolver(container, data));
1566
+ container.set(CORE_VIEW_TOKEN, engine);
1567
+ container.set(CORE_VIEW_RENDERER_TOKEN, new ViewRenderer(engine, layout));
1568
+ container.set(CORE_WEB_ERROR_VIEW_TOKEN2, createWebErrorView({
1569
+ render: customErrorRender ?? ((input) => engine.render(errorTemplateName(input.status), {
1570
+ title: input.title,
1571
+ message: input.message,
1572
+ errors: input.errors
1573
+ }, { layout, request: input.request }))
1574
+ }));
1575
+ }
1576
+ };
1577
+ }
1369
1578
 
1370
1579
  // ../../src/bootstrap/providers/index.ts
1371
- var coreProviders = [
1372
- config_default,
1373
- tracing_default,
1374
- cache_default,
1375
- storage_default,
1376
- auth_default,
1377
- events_default,
1378
- policy_default,
1379
- queue_default,
1380
- listeners_default,
1381
- viewProvider
1382
- ];
1580
+ function createCoreProviders(env = process.env) {
1581
+ env = Object.freeze({ ...env });
1582
+ const configProvider = createConfigProvider(env);
1583
+ const cacheProvider = createCacheProvider(env);
1584
+ const storageProvider = createStorageProvider(createStorageDriver2(resolveStorageConfig(env)));
1585
+ return [
1586
+ configProvider,
1587
+ createTracingProvider({ env }),
1588
+ cacheProvider,
1589
+ storageProvider,
1590
+ auth_default,
1591
+ policy_default,
1592
+ createQueueProvider(env),
1593
+ createViewProvider({ env })
1594
+ ];
1595
+ }
1383
1596
 
1384
1597
  // ../../src/bootstrap/context.ts
1385
- function collectProviders(modules = discoverModules()) {
1386
- return [...coreProviders, ...modules.flatMap((module) => module.providers ?? [])];
1598
+ function collectProviders(modules = []) {
1599
+ return [...createCoreProviders(), ...modules.flatMap((module) => module.providers ?? [])];
1387
1600
  }
1388
1601
  async function runProviderPhase(providers, phase, context) {
1389
1602
  for (const provider of providers)
1390
1603
  await provider[phase]?.(context);
1391
1604
  }
1392
- var readyContext;
1393
- async function createAppContext(providers) {
1394
- if (!providers)
1395
- await ensureModulesLoaded();
1396
- const configured = [...providers ?? collectProviders()];
1605
+ function createApplicationContext(providers, options) {
1606
+ if (!options)
1607
+ throw new TypeError("Explicit application definition and connection are required.");
1608
+ const configured = [...providers];
1397
1609
  const container = new ServiceContainer;
1398
1610
  const config = new ConfigStore;
1399
- const dependencies = { container };
1400
- const cleanups = [];
1401
- const drains = [];
1402
- let drainStarted = false;
1403
- let draining;
1404
- const drain = () => {
1405
- drainStarted = true;
1406
- draining ??= (async () => {
1407
- const errors = [];
1408
- for (const handler of drains.splice(0).reverse()) {
1409
- try {
1410
- await handler();
1411
- } catch (error) {
1412
- errors.push(error);
1413
- }
1414
- }
1415
- if (errors.length)
1416
- throw new AggregateError(errors, "Provider drain failed.");
1417
- })();
1418
- return draining;
1419
- };
1420
- const flushes = [];
1421
- let flushStarted = false;
1422
- let flushing;
1423
- const flush = () => {
1424
- flushStarted = true;
1425
- flushing ??= (async () => {
1426
- const errors = [];
1427
- for (const handler of flushes.splice(0).reverse()) {
1428
- try {
1429
- await handler();
1430
- } catch (error) {
1431
- errors.push(error);
1432
- }
1433
- }
1434
- if (errors.length)
1435
- throw new AggregateError(errors, "Provider flush failed.");
1436
- })();
1437
- return flushing;
1611
+ if (options.http)
1612
+ container.set(HTTP_PERSISTENCE_OPTIONS, Object.freeze({ ...options.http }));
1613
+ const cleanups = {
1614
+ drain: [],
1615
+ flush: [],
1616
+ close: []
1438
1617
  };
1439
- let disposal;
1440
- let disposed = false;
1441
- let initialized;
1442
- const dispose = () => {
1443
- disposed = true;
1444
- disposal ??= (async () => {
1445
- await drain();
1618
+ const started = new Set;
1619
+ const results = new Map;
1620
+ const phase = (name) => {
1621
+ const old = results.get(name);
1622
+ if (old)
1623
+ return old;
1624
+ started.add(name);
1625
+ const result = Promise.resolve().then(async () => {
1446
1626
  const errors = [];
1447
- try {
1448
- await flush();
1449
- } catch (error) {
1450
- errors.push(error);
1451
- }
1452
- if (initialized) {
1453
- clearActiveApplicationContext(initialized);
1454
- if (readyContext === initialized)
1455
- readyContext = undefined;
1456
- }
1457
- for (const handler of cleanups.splice(0).reverse()) {
1627
+ for (const callback of cleanups[name].splice(0).reverse()) {
1458
1628
  try {
1459
- await handler();
1629
+ await callback();
1460
1630
  } catch (error) {
1461
1631
  errors.push(error);
1462
1632
  }
1463
1633
  }
1464
1634
  if (errors.length)
1465
- throw new AggregateError(errors, "Provider cleanup failed.");
1466
- })();
1467
- return disposal;
1635
+ throw new AggregateError(errors, `Provider ${name} failed.`);
1636
+ });
1637
+ results.set(name, result);
1638
+ result.catch(() => {});
1639
+ return result;
1468
1640
  };
1641
+ let application;
1642
+ const invoke = (envelope, work) => createPersistenceInvocation(application, options.connection)(envelope, work);
1643
+ const dependencies = { container, invoke };
1469
1644
  const context = {
1470
1645
  container,
1471
1646
  config,
1472
1647
  dependencies,
1473
- onCleanup(handler, phase = "close") {
1474
- if (disposed)
1475
- throw new Error("Cannot register cleanup on a disposed application context.");
1476
- if (phase !== "drain" && phase !== "flush" && phase !== "close")
1648
+ invoke,
1649
+ onCleanup(callback, name = "close") {
1650
+ if (!["drain", "flush", "close"].includes(name))
1477
1651
  throw new TypeError("Unknown provider cleanup phase.");
1478
- if (phase === "drain" && drainStarted || phase === "flush" && flushStarted)
1652
+ if (started.has("close"))
1653
+ throw new Error("Cannot register cleanup on a disposed application context.");
1654
+ if (started.has(name))
1479
1655
  throw new Error("Cannot register cleanup after its phase started.");
1480
- (phase === "drain" ? drains : phase === "flush" ? flushes : cleanups).push(handler);
1656
+ cleanups[name].push(callback);
1481
1657
  }
1482
1658
  };
1483
- container.set(CORE_HTTP_CLEANUP_TOKEN2, (handler) => context.onCleanup(handler));
1484
- try {
1485
- await runProviderPhase(configured, "register", context);
1486
- await runProviderPhase(configured, "boot", context);
1487
- assertAppDependenciesComplete(dependencies);
1488
- const appContext = {
1489
- container,
1490
- config,
1491
- dependencies,
1492
- drain,
1493
- flush,
1494
- dispose
1495
- };
1496
- initialized = appContext;
1497
- setActiveApplicationContext(appContext);
1498
- readyContext = appContext;
1499
- return appContext;
1500
- } catch (error) {
1501
- try {
1502
- await dispose();
1503
- } catch (cleanupError) {
1504
- throw new AggregateError([error, cleanupError], "Application startup and cleanup failed.", {
1505
- cause: error
1659
+ container.set(CORE_HTTP_CLEANUP_TOKEN2, (callback) => context.onCleanup(callback));
1660
+ application = createApplication({
1661
+ ...options.definition,
1662
+ providers: [
1663
+ ...options.definition.providers,
1664
+ {
1665
+ name: "bootstrap.providers",
1666
+ setup: async (scope) => {
1667
+ await scope.acquire({
1668
+ name: "bootstrap.providers",
1669
+ open: () => ({ ok: true, value: context }),
1670
+ drain: () => phase("drain"),
1671
+ flush: () => phase("flush"),
1672
+ close: () => phase("close")
1673
+ });
1674
+ const selected = [...configured, ...options.providersFromScope?.(scope) ?? []];
1675
+ await runProviderPhase(selected, "register", context);
1676
+ await runProviderPhase(selected, "boot", context);
1677
+ assertAppDependenciesComplete(dependencies);
1678
+ }
1679
+ }
1680
+ ]
1681
+ });
1682
+ options.onConstructed?.(Object.freeze({ application, invoke }));
1683
+ let startup;
1684
+ return Object.freeze({
1685
+ application,
1686
+ invoke,
1687
+ start: () => startup ??= (async () => {
1688
+ await application.start();
1689
+ assertAppDependenciesComplete(dependencies);
1690
+ return Object.freeze({
1691
+ container,
1692
+ config,
1693
+ dependencies,
1694
+ application,
1695
+ invoke,
1696
+ drain: () => phase("drain"),
1697
+ flush: () => phase("flush"),
1698
+ dispose: async () => {
1699
+ const result = await application.stop();
1700
+ if (!result.successful)
1701
+ throw new Error("Application shutdown is incomplete.");
1702
+ }
1506
1703
  });
1507
- }
1508
- throw error;
1509
- }
1704
+ })()
1705
+ });
1706
+ }
1707
+ async function createAppContext(providers, options) {
1708
+ const selected = providers ?? collectProviders();
1709
+ return createApplicationContext(selected, options).start();
1510
1710
  }
1511
1711
  // ../../src/bootstrap/createWebRoutes.ts
1512
- import { join as join5 } from "path";
1513
- import { isViewsEnabled as isViewsEnabled3 } from "@getstrata/core/runtime/frontendMode";
1712
+ import { resolve as resolve3 } from "path";
1713
+ import { isViewsEnabled } from "@getstrata/core/runtime/frontendMode";
1514
1714
  import { assertUrlPathUnderRoot } from "@getstrata/core/security/safePath";
1515
1715
  import { notFoundHtmlResponse } from "@getstrata/core/view";
1516
- function registerRoute(method, path, middleware) {
1517
- routeRegistry.register({ method, path, middleware });
1518
- }
1716
+ import { CORE_WEB_ERROR_VIEW_TOKEN as CORE_WEB_ERROR_VIEW_TOKEN3 } from "@getstrata/core/view/tokens";
1519
1717
  function createWebRoutes(dependencies, options = {}) {
1520
1718
  const wrappedRoutes = buildWebModuleRoutes(dependencies, {
1521
- clearRegistry: false,
1522
- modules: options.modules
1719
+ modules: options.modules ?? []
1523
1720
  });
1524
- registerRoute("GET", "/", ["global", "web"]);
1525
- wrappedRoutes["/assets/*"] = async (request) => {
1526
- registerRoute("GET", "/assets/*", ["global", "web"]);
1721
+ const publicDir = resolve3(options.publicDir ?? "public");
1722
+ const renderError = dependencies.container.has(CORE_WEB_ERROR_VIEW_TOKEN3) ? dependencies.container.resolve(CORE_WEB_ERROR_VIEW_TOKEN3) : undefined;
1723
+ const assetHandler = async (request) => {
1527
1724
  const pathname = new URL(request.url).pathname;
1528
1725
  try {
1529
- const filePath = assertUrlPathUnderRoot(join5(process.cwd(), "public"), pathname);
1726
+ const filePath = assertUrlPathUnderRoot(publicDir, pathname);
1530
1727
  const file = Bun.file(filePath);
1531
1728
  if (!await file.exists()) {
1532
- return notFoundHtmlResponse();
1729
+ return notFoundHtmlResponse(undefined, renderError);
1533
1730
  }
1534
1731
  return new Response(file);
1535
1732
  } catch {
1536
- return notFoundHtmlResponse();
1733
+ return notFoundHtmlResponse(undefined, renderError);
1537
1734
  }
1538
1735
  };
1539
- registerRoute("GET", "/assets/*", ["global", "web"]);
1540
- return wrappedRoutes;
1736
+ const plan = compileRoutePlan([
1737
+ { name: "web modules", routes: wrappedRoutes },
1738
+ { name: "public assets", routes: { "/assets/*": assetHandler }, middleware: [] }
1739
+ ]);
1740
+ return publishRoutePlan(plan, plan.routes);
1541
1741
  }
1542
1742
  function mergeWebRoutes(dependencies, routes, options = {}) {
1543
- if (!isViewsEnabled3()) {
1743
+ if (!isViewsEnabled()) {
1544
1744
  return routes;
1545
1745
  }
1546
- return {
1547
- ...createWebRoutes(dependencies, options),
1548
- ...routes
1549
- };
1746
+ const webRoutes = createWebRoutes(dependencies, options);
1747
+ const plan = compileRoutePlan([
1748
+ { name: "web", routes: webRoutes },
1749
+ { name: "application", routes }
1750
+ ]);
1751
+ return publishRoutePlan(plan, plan.routes);
1550
1752
  }
1551
1753
  // ../../src/bootstrap/dependencies.ts
1552
- async function createAppDependencies() {
1553
- return (await createAppContext()).dependencies;
1754
+ async function createAppDependencies(providers, options) {
1755
+ return (await createAppContext(providers, options)).dependencies;
1554
1756
  }
1555
1757
  // ../../src/bootstrap/discoverModels.ts
1556
- import { readdir as readdir3 } from "fs/promises";
1557
- import { join as join6 } from "path";
1758
+ import { readdir as readdir2 } from "fs/promises";
1759
+ import { join as join3 } from "path";
1558
1760
  import { pathToFileURL as pathToFileURL2 } from "url";
1559
- import { bootModels, Model } from "@getstrata/core/database/model";
1560
- async function discoverModels(directory = join6(process.cwd(), "src", "models"), options = {}) {
1761
+ import { assertDefinition } from "@getstrata/core/database/definitions";
1762
+ async function discoverModels(directory = join3(process.cwd(), "src", "models"), options = {}) {
1561
1763
  const excluded = new Set([
1562
1764
  "register.ts",
1563
1765
  "register.js",
@@ -1567,29 +1769,118 @@ async function discoverModels(directory = join6(process.cwd(), "src", "models"),
1567
1769
  ]);
1568
1770
  const models = new Set;
1569
1771
  async function visit(path) {
1570
- const entries = await readdir3(path, { withFileTypes: true });
1772
+ const entries = await readdir2(path, { withFileTypes: true });
1571
1773
  entries.sort((a, b) => a.name.localeCompare(b.name));
1572
1774
  for (const entry of entries) {
1573
- const file = join6(path, entry.name);
1775
+ const file = join3(path, entry.name);
1574
1776
  if (entry.isDirectory())
1575
1777
  await visit(file);
1576
1778
  else if (!excluded.has(entry.name) && entry.isFile() && /\.(ts|js|mts|mjs)$/.test(entry.name) && !/\.d\.[cm]?ts$/.test(entry.name)) {
1577
1779
  const exports = await import(pathToFileURL2(file).href);
1578
1780
  for (const value of Object.values(exports)) {
1579
- if (typeof value === "function" && value.prototype instanceof Model)
1781
+ if (value && typeof value === "object" && Object.getOwnPropertyDescriptor(value, "kind")?.value === "model") {
1782
+ assertDefinition(value, "model");
1580
1783
  models.add(value);
1784
+ }
1581
1785
  }
1582
1786
  }
1583
1787
  }
1584
1788
  }
1585
1789
  await visit(directory);
1586
1790
  const result = [...models];
1587
- bootModels(result);
1588
1791
  return result;
1589
1792
  }
1793
+ // ../../src/bootstrap/discoverModules.ts
1794
+ import { readdir as readdir3 } from "fs/promises";
1795
+ import { join as join4, resolve as resolve4 } from "path";
1796
+ function validateModule(value, location) {
1797
+ if (!value || typeof value !== "object" || Array.isArray(value))
1798
+ throw new TypeError(`Invalid application module at ${location}.`);
1799
+ const module = value;
1800
+ if (typeof module.name !== "string" || !module.name.trim())
1801
+ throw new TypeError(`Invalid module name at ${location}.`);
1802
+ if (module.order !== undefined && (typeof module.order !== "number" || !Number.isFinite(module.order)))
1803
+ throw new TypeError(`Invalid module order at ${location}.`);
1804
+ for (const hook of ["routes", "webRoutes"])
1805
+ if (module[hook] !== undefined && typeof module[hook] !== "function")
1806
+ throw new TypeError(`Invalid ${hook} at ${location}.`);
1807
+ if (module.providers !== undefined) {
1808
+ if (!Array.isArray(module.providers))
1809
+ throw new TypeError(`Invalid providers at ${location}.`);
1810
+ for (const provider of module.providers) {
1811
+ if (!provider || typeof provider.name !== "string" || !provider.name.trim() || provider.register !== undefined && typeof provider.register !== "function" || provider.boot !== undefined && typeof provider.boot !== "function")
1812
+ throw new TypeError(`Invalid provider at ${location}.`);
1813
+ }
1814
+ }
1815
+ }
1816
+ async function load2(options) {
1817
+ const manifest = options.manifest;
1818
+ const entries = [];
1819
+ if (manifest)
1820
+ for (const [index, value] of manifest.entries())
1821
+ entries.push({ value, location: `module manifest[${index}]` });
1822
+ else {
1823
+ const directory = options.modulesDir;
1824
+ if (!directory)
1825
+ throw new Error("An explicit modulesDir or manifest is required to discover modules.");
1826
+ let folders;
1827
+ try {
1828
+ folders = await readdir3(directory, { withFileTypes: true });
1829
+ } catch (error) {
1830
+ if (error.code === "ENOENT")
1831
+ return Object.freeze([]);
1832
+ throw error;
1833
+ }
1834
+ const excluded = new Set(options.exclude ?? []);
1835
+ for (const folder of folders.filter((entry) => entry.isDirectory() && !excluded.has(entry.name)).sort((a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0)) {
1836
+ const path = join4(directory, folder.name);
1837
+ const files = await readdir3(path);
1838
+ const candidates = files.filter((file) => /^index\.(ts|js|mts|mjs)$/.test(file));
1839
+ if (candidates.length !== 1)
1840
+ throw new Error(`Expected one module entrypoint at ${path}; found ${candidates.length}.`);
1841
+ const file = join4(path, candidates[0]);
1842
+ const exports = await importInfrastructure(file);
1843
+ entries.push({ value: exports.default, location: file });
1844
+ }
1845
+ }
1846
+ const names = new Map;
1847
+ const modules = [];
1848
+ for (const { value, location } of entries) {
1849
+ validateModule(value, location);
1850
+ const previous = names.get(value.name);
1851
+ if (previous)
1852
+ throw new Error(`Duplicate module "${value.name}" at ${location}; first declared at ${previous}.`);
1853
+ names.set(value.name, location);
1854
+ modules.push(value);
1855
+ }
1856
+ return Object.freeze(modules.sort((left, right) => (left.order ?? 100) - (right.order ?? 100)));
1857
+ }
1858
+ function createModuleDiscovery(options) {
1859
+ const source = Object.freeze({
1860
+ ...options,
1861
+ modulesDir: options.modulesDir === undefined ? undefined : resolve4(options.modulesDir),
1862
+ manifest: options.manifest === undefined ? undefined : Object.freeze([...options.manifest]),
1863
+ exclude: options.exclude === undefined ? undefined : Object.freeze([...options.exclude])
1864
+ });
1865
+ let pending;
1866
+ return Object.freeze({
1867
+ load() {
1868
+ if (pending)
1869
+ return pending;
1870
+ const result = load2(source).catch((error) => {
1871
+ if (pending === result)
1872
+ pending = undefined;
1873
+ throw error;
1874
+ });
1875
+ pending = result;
1876
+ return result;
1877
+ }
1878
+ });
1879
+ }
1880
+ function ensureModulesLoaded(options) {
1881
+ return createModuleDiscovery(options).load();
1882
+ }
1590
1883
  // ../../src/bootstrap/health.ts
1591
- import { getBoundDatabaseConnection } from "@getstrata/core/database/boundConnection";
1592
- import { getDefaultDatabasePool } from "@getstrata/core/database/defaultConnection";
1593
1884
  import { jsonResponse } from "@getstrata/core/http/response";
1594
1885
  import { envFlagEnabled as envFlagEnabled2 } from "@getstrata/core/runtime/appEnv";
1595
1886
  var {RedisClient } = globalThis.Bun;
@@ -1601,35 +1892,16 @@ function resolveRedisUrl(dependencies) {
1601
1892
  const redisUrl = config.get(REDIS_URL_CONFIG_KEY)?.trim();
1602
1893
  return redisUrl || undefined;
1603
1894
  }
1604
- function resolveHealthDatabase() {
1605
- const bound = getBoundDatabaseConnection();
1606
- if (bound) {
1607
- return bound;
1608
- }
1609
- try {
1610
- return getDefaultDatabasePool();
1611
- } catch {
1612
- return null;
1613
- }
1614
- }
1615
- async function pingDatabaseClient(connection) {
1895
+ async function pingDatabase(invoke) {
1616
1896
  try {
1617
- await connection.unsafe("SELECT 1");
1618
- return true;
1897
+ return await invoke({ kind: "request", actor: { kind: "system", policy: "http.health" } }, async ({ database }) => {
1898
+ await database.execute({ text: "SELECT 1", params: [] });
1899
+ return true;
1900
+ });
1619
1901
  } catch {
1620
1902
  return false;
1621
1903
  }
1622
1904
  }
1623
- async function checkDatabase() {
1624
- const connection = resolveHealthDatabase();
1625
- if (!connection) {
1626
- return false;
1627
- }
1628
- return await pingDatabaseClient(connection);
1629
- }
1630
- async function pingDatabase() {
1631
- return await checkDatabase();
1632
- }
1633
1905
  async function checkRedis(redisUrl) {
1634
1906
  let client;
1635
1907
  try {
@@ -1652,11 +1924,10 @@ async function resolveExtraFields(extra) {
1652
1924
  }
1653
1925
  return typeof extra === "function" ? await extra() : extra;
1654
1926
  }
1655
- async function collectDependencyChecks(dependencies) {
1927
+ async function collectDependencyChecks(dependencies, redisUrl) {
1656
1928
  const checks = {
1657
- database: await checkDatabase() ? "ok" : "error"
1929
+ database: await pingDatabase(dependencies.invoke) ? "ok" : "error"
1658
1930
  };
1659
- const redisUrl = resolveRedisUrl(dependencies);
1660
1931
  if (redisUrl) {
1661
1932
  checks.redis = await checkRedis(redisUrl) ? "ok" : "error";
1662
1933
  } else {
@@ -1666,6 +1937,9 @@ async function collectDependencyChecks(dependencies) {
1666
1937
  return { checks, ready };
1667
1938
  }
1668
1939
  function createHealthRoutes(dependencies, options = {}) {
1940
+ const redisUrl = resolveRedisUrl(dependencies);
1941
+ const config = dependencies.container.has(CORE_CONFIG_TOKEN) ? dependencies.container.resolve(CORE_CONFIG_TOKEN) : undefined;
1942
+ const debug = config ? config.get("app.debug") === true : envFlagEnabled2(process.env.APP_DEBUG);
1669
1943
  return {
1670
1944
  "/health": async (request) => {
1671
1945
  if (request && request.method !== "GET" && request.method !== "HEAD") {
@@ -1678,7 +1952,7 @@ function createHealthRoutes(dependencies, options = {}) {
1678
1952
  headers: { ...headers, "content-type": "text/plain; charset=utf-8" }
1679
1953
  }) : jsonResponse({ status: "ok", ...extra }, { headers });
1680
1954
  }
1681
- const { checks, ready: dependenciesReady } = await collectDependencyChecks(dependencies);
1955
+ const { checks, ready: dependenciesReady } = await collectDependencyChecks(dependencies, redisUrl);
1682
1956
  let schemaReady = true;
1683
1957
  if (options.schemaCheck) {
1684
1958
  try {
@@ -1704,8 +1978,7 @@ function createHealthRoutes(dependencies, options = {}) {
1704
1978
  },
1705
1979
  "/ready": async () => {
1706
1980
  const extra = await resolveExtraFields(options.extra);
1707
- const { checks, ready } = await collectDependencyChecks(dependencies);
1708
- const debug = envFlagEnabled2(process.env.APP_DEBUG);
1981
+ const { checks, ready } = await collectDependencyChecks(dependencies, redisUrl);
1709
1982
  return jsonResponse({
1710
1983
  status: ready ? "ready" : "not_ready",
1711
1984
  ...debug ? { checks, ...extra } : {}
@@ -1713,6 +1986,7 @@ function createHealthRoutes(dependencies, options = {}) {
1713
1986
  }
1714
1987
  };
1715
1988
  }
1989
+ var checkDatabase = pingDatabase;
1716
1990
  // ../../src/bootstrap/http/securedRouteModelBinding.ts
1717
1991
  import {
1718
1992
  securedBindRouteModel,
@@ -1724,7 +1998,7 @@ import { resolveMembershipService } from "@getstrata/core/auth/membershipService
1724
1998
  import { timingSafeEqual } from "crypto";
1725
1999
  import {
1726
2000
  renderTransactionAcquisitionMetrics
1727
- } from "@getstrata/core/database/transaction";
2001
+ } from "@getstrata/core/database/acquisitionMetrics";
1728
2002
  import { renderOutboxMetrics } from "@getstrata/core/events/outbox";
1729
2003
  import { prometheusRegistry } from "@getstrata/core/metrics/prometheus";
1730
2004
  import {
@@ -1732,7 +2006,7 @@ import {
1732
2006
  renderFailedJobMetrics,
1733
2007
  renderRedisQueueMetrics
1734
2008
  } from "@getstrata/core/queue/queueMetrics";
1735
- import { isProductionEnv } from "@getstrata/core/runtime/appEnv";
2009
+ import { isProductionEnv as isProductionEnv2 } from "@getstrata/core/runtime/appEnv";
1736
2010
  import {
1737
2011
  renderTracingMetrics
1738
2012
  } from "@getstrata/core/tracing/tracingMiddleware";
@@ -1774,19 +2048,23 @@ function tokensMatch(left, right) {
1774
2048
  }
1775
2049
  return timingSafeEqual(leftBuffer, rightBuffer);
1776
2050
  }
1777
- function authorizeMetrics(request) {
1778
- const expected = process.env.METRICS_TOKEN?.trim();
2051
+ function authorizeMetrics(request, policy) {
2052
+ const expected = policy.token;
1779
2053
  const authorization = request.headers.get("authorization") ?? "";
1780
2054
  const presented = authorization.startsWith("Bearer ") ? authorization.slice("Bearer ".length) : "";
1781
2055
  if (expected) {
1782
2056
  return presented.length > 0 && tokensMatch(presented, expected);
1783
2057
  }
1784
- if (isProductionEnv()) {
2058
+ if (policy.production) {
1785
2059
  return false;
1786
2060
  }
1787
2061
  return true;
1788
2062
  }
1789
2063
  function createMetricsRoutes(options = {}) {
2064
+ const authorization = Object.freeze({
2065
+ token: (options.authorization?.token ?? (options.authorization ? undefined : process.env.METRICS_TOKEN))?.trim(),
2066
+ production: options.authorization?.production ?? isProductionEnv2()
2067
+ });
1790
2068
  let collection;
1791
2069
  const collect = () => {
1792
2070
  if (!options.queue && !options.outbox && !options.tracing && !options.transactionAcquisition && !options.failedJobs)
@@ -1808,7 +2086,7 @@ strata_${name}_collector_success 0
1808
2086
  };
1809
2087
  return {
1810
2088
  "/metrics": async (request) => {
1811
- if (!authorizeMetrics(request)) {
2089
+ if (!authorizeMetrics(request, authorization)) {
1812
2090
  return new Response("Not Found", { status: 404 });
1813
2091
  }
1814
2092
  return new Response(prometheusRegistry.renderMetrics() + await collect(), {
@@ -1821,14 +2099,97 @@ strata_${name}_collector_success 0
1821
2099
  }
1822
2100
  };
1823
2101
  }
2102
+ // ../../src/bootstrap/prefixRouteMap.ts
2103
+ function prefixRouteMap(prefix, routes) {
2104
+ const normalizedPrefix = prefix.replace(/\/$/, "");
2105
+ const prefixed = {};
2106
+ for (const [path, handler] of Object.entries(routes)) {
2107
+ const normalizedPath = path.startsWith("/") ? path : `/${path}`;
2108
+ prefixed[`${normalizedPrefix}${normalizedPath}`] = handler;
2109
+ }
2110
+ return prefixed;
2111
+ }
2112
+ // ../../src/bootstrap/providers/cache.ts
2113
+ import {
2114
+ createCacheStore as createCacheStore2,
2115
+ snapshotCacheStoreOptions as snapshotCacheStoreOptions2
2116
+ } from "@getstrata/core/cache/createCacheStore";
2117
+ import { CacheRepository as CacheRepository2, createGuardedCache } from "@getstrata/core/cache/repository";
2118
+ import { CORE_CACHE_BACKEND_TOKEN, CORE_CACHE_TOKEN as CORE_CACHE_TOKEN2 } from "@getstrata/core/cache/tokens";
2119
+ import { CORE_EXECUTION_OPERATIONS_TOKEN } from "@getstrata/core/contracts/executionOperations";
2120
+ import {
2121
+ resourceService,
2122
+ service as service2
2123
+ } from "@getstrata/core/contracts/services";
2124
+ function createCacheBindings(options) {
2125
+ const snapshot = snapshotCacheStoreOptions2(options, true);
2126
+ return Object.freeze([
2127
+ resourceService(CORE_CACHE_BACKEND_TOKEN, {
2128
+ lifetime: "application",
2129
+ dependencies: [],
2130
+ create: () => ({
2131
+ name: "core.cache.backend",
2132
+ open: () => ({ ok: true, value: new CacheRepository2(createCacheStore2(snapshot)) }),
2133
+ close: (backend) => backend.close()
2134
+ })
2135
+ }),
2136
+ service2(CORE_CACHE_TOKEN2, {
2137
+ lifetime: "execution",
2138
+ dependencies: [CORE_CACHE_BACKEND_TOKEN, CORE_EXECUTION_OPERATIONS_TOKEN],
2139
+ create: (backend, operations) => createGuardedCache(backend, operations)
2140
+ })
2141
+ ]);
2142
+ }
2143
+ // ../../src/bootstrap/providers/mail.ts
2144
+ import { service as service3 } from "@getstrata/core/contracts/services";
2145
+ import {
2146
+ CORE_MAIL_TOKEN,
2147
+ LogMailDriver,
2148
+ Mailer,
2149
+ SmtpMailDriver,
2150
+ snapshotSmtpConfig
2151
+ } from "@getstrata/core/mail/mailer";
2152
+ function createMailBindings(options) {
2153
+ let create;
2154
+ if (options.driver === "smtp") {
2155
+ const snapshot = snapshotSmtpConfig(options.smtp);
2156
+ create = () => new SmtpMailDriver(snapshot);
2157
+ } else if (options.driver === "log")
2158
+ create = () => new LogMailDriver;
2159
+ else if (options.driver === "custom" && options.mail && typeof options.mail.send === "function") {
2160
+ const driver = options.mail;
2161
+ create = () => driver;
2162
+ } else
2163
+ throw new TypeError("Unknown mail driver or missing custom send capability.");
2164
+ return Object.freeze([
2165
+ service3(CORE_MAIL_TOKEN, {
2166
+ lifetime: "application",
2167
+ dependencies: [],
2168
+ create: () => new Mailer(create())
2169
+ })
2170
+ ]);
2171
+ }
2172
+ // ../../src/bootstrap/routePlan.ts
2173
+ function compileRouteMap(routes, options = {}) {
2174
+ if (options.middleware !== undefined || options.metadata !== undefined) {
2175
+ try {
2176
+ getRouteInventory(routes);
2177
+ } catch {
2178
+ return compileRoutePlan([{ name: "routes", routes, ...options }]).routes;
2179
+ }
2180
+ throw new Error("Cannot replace contracts or middleware on an already compiled route map");
2181
+ }
2182
+ return compileRoutePlan([{ name: "routes", routes }]).routes;
2183
+ }
2184
+ function composeRouteMaps(...maps) {
2185
+ return compileRoutePlan(maps.map((routes, index) => ({ name: `routes ${index + 1}`, routes }))).routes;
2186
+ }
1824
2187
  // ../../src/bootstrap/secretsGuard.ts
1825
2188
  import { resolveFieldEncryptionKeyring } from "@getstrata/core/crypto/fieldEncryption";
1826
- import { getDefaultDatabasePool as getDefaultDatabasePool2 } from "@getstrata/core/database/defaultConnection";
1827
- import { envFlagEnabled as envFlagEnabled3, isProductionEnv as isProductionEnv2 } from "@getstrata/core/runtime/appEnv";
1828
- import { isViewsMode, parseFrontendMode } from "@getstrata/core/runtime/frontendMode";
2189
+ import { envFlagEnabled as envFlagEnabled3, isProductionEnv as isProductionEnv3 } from "@getstrata/core/runtime/appEnv";
2190
+ import { isViewsMode as isViewsMode2, parseFrontendMode as parseFrontendMode3 } from "@getstrata/core/runtime/frontendMode";
1829
2191
  import {
1830
2192
  assertPostgresRoleCannotBypassRls,
1831
- inspectCurrentPostgresRole,
1832
2193
  isPostgresUrl,
1833
2194
  postgresUrlUsername
1834
2195
  } from "@getstrata/core/tenant/enableTenantRls";
@@ -1845,6 +2206,7 @@ var PUBLISHED_TEST_SCIM_TOKENS = new Set([PUBLISHED_TEST_SCIM_BEARER_TOKEN]);
1845
2206
  var PLACEHOLDER_SECRET_PATTERN = /change-me/i;
1846
2207
  var SECRETS_TO_ROTATE = [
1847
2208
  "SESSION_SECRET",
2209
+ "SIGNED_URL_SECRET",
1848
2210
  "TOKEN_HASH_PEPPER",
1849
2211
  "METRICS_TOKEN",
1850
2212
  "SCIM_BEARER_TOKEN",
@@ -2004,7 +2366,7 @@ function assertPublicAppUrl(env) {
2004
2366
  }
2005
2367
  function assertProductionSecrets(env = process.env) {
2006
2368
  resolveFieldEncryptionKeyring(env);
2007
- if (!isProductionEnv2(env)) {
2369
+ if (!isProductionEnv3(env)) {
2008
2370
  return;
2009
2371
  }
2010
2372
  assertNoPlaceholderSecrets(env);
@@ -2017,7 +2379,7 @@ function assertProductionSecrets(env = process.env) {
2017
2379
  assertTokenAuthProductionSecrets(env);
2018
2380
  }
2019
2381
  assertFeatureProductionSecrets(env);
2020
- if (isViewsMode(parseFrontendMode(env.FRONTEND_MODE))) {
2382
+ if (isViewsMode2(parseFrontendMode3(env.FRONTEND_MODE))) {
2021
2383
  assertSessionSecret(env);
2022
2384
  }
2023
2385
  assertRlsUsesAppDatabaseRole(env);
@@ -2056,7 +2418,7 @@ async function parseFormBody(request) {
2056
2418
  }
2057
2419
  // ../../src/bootstrap/web/routing.ts
2058
2420
  import { requestPrefersJson } from "@getstrata/core/http/contentNegotiation";
2059
- import { withErrorHandling as withErrorHandling2 } from "@getstrata/core/http/response";
2421
+ import { identityModes as identityModes3, scimMiddleware as scimMiddleware3 } from "#strata-http-route";
2060
2422
  function routeParams(request) {
2061
2423
  const raw = request.params;
2062
2424
  if (!raw || typeof raw !== "object")
@@ -2073,8 +2435,8 @@ function toRouteRequest(request) {
2073
2435
  });
2074
2436
  return request;
2075
2437
  }
2076
- function wrapSecuredRouteModelByKey(param, resolver, authorization, handler) {
2077
- const bound = withErrorHandling2(securedBindRouteModelByKey(param, resolver, authorization, handler));
2438
+ function wrapSecuredRouteModelByKey(param, resolver, authorization, handler, ports) {
2439
+ const bound = securedBindRouteModelByKey(param, resolver, authorization, handler, ports);
2078
2440
  return async (request) => bound(toRouteRequest(request));
2079
2441
  }
2080
2442
  function wrapWebLogin(kernel, handler, onThrottled) {
@@ -2085,23 +2447,28 @@ function wrapWebRegister(kernel, handler, onThrottled) {
2085
2447
  }
2086
2448
  function wrapWebThrottle(kernel, scope, handler, onThrottled) {
2087
2449
  const throttled = scope === "login" ? kernel.wrapLogin(handler) : kernel.wrapRegister(handler);
2088
- return async (request) => {
2089
- const response = await throttled(request);
2450
+ return kernel.composed(async (request, ports) => {
2451
+ const response = await throttled(request, ports);
2090
2452
  if (response.status === 429 && !requestPrefersJson(request)) {
2091
- return onThrottled(request);
2453
+ return onThrottled(request, ports);
2092
2454
  }
2093
2455
  return response;
2094
- };
2456
+ }, "web", identityModes3(handler), scimMiddleware3(handler));
2095
2457
  }
2096
2458
  function createRouteKernel(dependencies) {
2097
2459
  return createHttpKernel(dependencies);
2098
2460
  }
2099
2461
  // ../../src/bootstrap/web/server.ts
2100
- import { resolveMaxBodyBytes } from "@getstrata/core/http/bodySizeLimitMiddleware";
2101
- import { createCorsMiddleware as createCorsMiddleware2 } from "@getstrata/core/http/corsMiddleware";
2462
+ import { resolve as resolve5 } from "path";
2463
+ import { resolveMaxBodyBytes as resolveMaxBodyBytes2 } from "@getstrata/core/http/bodySizeLimitMiddleware";
2464
+ import {
2465
+ createCorsMiddleware as createCorsMiddleware2,
2466
+ resolveCorsConfig as resolveCorsConfig3
2467
+ } from "@getstrata/core/http/corsMiddleware";
2102
2468
  import { currentRequestMeta as currentRequestMeta2, runWithRequestMeta } from "@getstrata/core/http/requestMetaContext";
2103
2469
  import { assertUrlPathUnderRoot as assertUrlPathUnderRoot2 } from "@getstrata/core/security/safePath";
2104
2470
  import { notFoundHtmlResponse as notFoundHtmlResponse2 } from "@getstrata/core/view";
2471
+ import { dispatchOwnedRoute } from "#strata-http-route";
2105
2472
  function socketAddress(server, request) {
2106
2473
  const address = server?.requestIP(request)?.address;
2107
2474
  return address ? address.replace(/^::ffff:/i, "") : null;
@@ -2109,7 +2476,7 @@ function socketAddress(server, request) {
2109
2476
  async function missingHtmlResponse() {
2110
2477
  return notFoundHtmlResponse2();
2111
2478
  }
2112
- function wrapRouteHandler(handler, path, onRequest, track = (work) => work()) {
2479
+ function wrapRouteHandler(handler, path, onRequest, track = (work) => work(), enter, validate) {
2113
2480
  return async (request, server) => {
2114
2481
  return await track(async () => await runWithRequestMeta({
2115
2482
  ...currentRequestMeta2(),
@@ -2119,15 +2486,24 @@ function wrapRouteHandler(handler, path, onRequest, track = (work) => work()) {
2119
2486
  peerAddress: socketAddress(server, request),
2120
2487
  userAgent: request.headers.get("user-agent")
2121
2488
  }, async () => {
2122
- const intercepted = await onRequest?.(request, server);
2123
- if (intercepted instanceof Response)
2124
- return intercepted;
2125
- const response = await handler(request, server);
2126
- return response ?? await missingHtmlResponse();
2489
+ const invalid = validate?.(request, server);
2490
+ if (invalid)
2491
+ return invalid;
2492
+ const owned = await dispatchOwnedRoute(handler, request, (ports) => onRequest?.(request, server, ports));
2493
+ if (owned)
2494
+ return owned;
2495
+ const work = async (_request, ports) => {
2496
+ const intercepted = await onRequest?.(request, server, ports);
2497
+ if (intercepted instanceof Response)
2498
+ return intercepted;
2499
+ const response = await handler(request, server, ports);
2500
+ return response ?? await missingHtmlResponse();
2501
+ };
2502
+ return enter ? enter(request, work) : work(request);
2127
2503
  }));
2128
2504
  };
2129
2505
  }
2130
- function convertAppRoutesToBunRoutes(routes, cors = {}, onRequest, track) {
2506
+ function convertAppRoutesToBunRoutes(routes, cors = {}, onRequest, track, enter, validate) {
2131
2507
  const bunRoutes = {};
2132
2508
  const middleware = createCorsMiddleware2(cors);
2133
2509
  const preflight = (request) => middleware(request, async () => new Response(null, { status: 405 }));
@@ -2135,16 +2511,16 @@ function convertAppRoutesToBunRoutes(routes, cors = {}, onRequest, track) {
2135
2511
  if (handler instanceof Response) {
2136
2512
  const methods = {};
2137
2513
  for (const method of ["GET", "HEAD", "POST", "PUT", "DELETE", "PATCH"]) {
2138
- methods[method] = wrapRouteHandler(() => handler.clone(), path, onRequest, track);
2514
+ methods[method] = wrapRouteHandler(() => handler.clone(), path, onRequest, track, enter, validate);
2139
2515
  }
2140
- methods.OPTIONS = wrapRouteHandler(preflight, path, onRequest, track);
2516
+ methods.OPTIONS = wrapRouteHandler(preflight, path, onRequest, track, enter, validate);
2141
2517
  bunRoutes[path] = methods;
2142
2518
  continue;
2143
2519
  }
2144
2520
  if (typeof handler === "function") {
2145
2521
  bunRoutes[path] = {
2146
- GET: wrapRouteHandler(handler, path, onRequest, track),
2147
- OPTIONS: wrapRouteHandler(preflight, path, onRequest, track)
2522
+ GET: wrapRouteHandler(handler, path, onRequest, track, enter, validate),
2523
+ OPTIONS: wrapRouteHandler(preflight, path, onRequest, track, enter, validate)
2148
2524
  };
2149
2525
  continue;
2150
2526
  }
@@ -2152,16 +2528,16 @@ function convertAppRoutesToBunRoutes(routes, cors = {}, onRequest, track) {
2152
2528
  const methods = {};
2153
2529
  for (const [method, methodHandler] of Object.entries(handler)) {
2154
2530
  if (methodHandler instanceof Response) {
2155
- methods[method.toUpperCase()] = wrapRouteHandler(() => methodHandler.clone(), path, onRequest, track);
2531
+ methods[method.toUpperCase()] = wrapRouteHandler(() => methodHandler.clone(), path, onRequest, track, enter, validate);
2156
2532
  continue;
2157
2533
  }
2158
2534
  if (typeof methodHandler !== "function") {
2159
2535
  continue;
2160
2536
  }
2161
- methods[method.toUpperCase()] = wrapRouteHandler(methodHandler, path, onRequest, track);
2537
+ methods[method.toUpperCase()] = wrapRouteHandler(methodHandler, path, onRequest, track, enter, validate);
2162
2538
  }
2163
2539
  if (Object.keys(methods).length > 0) {
2164
- methods.OPTIONS ??= wrapRouteHandler(preflight, path, onRequest, track);
2540
+ methods.OPTIONS ??= wrapRouteHandler(preflight, path, onRequest, track, enter, validate);
2165
2541
  bunRoutes[path] = methods;
2166
2542
  }
2167
2543
  }
@@ -2169,10 +2545,13 @@ function convertAppRoutesToBunRoutes(routes, cors = {}, onRequest, track) {
2169
2545
  return bunRoutes;
2170
2546
  }
2171
2547
  function createWebServer(options) {
2548
+ return openWebServer(options);
2549
+ }
2550
+ function openWebServer(options, ownership) {
2172
2551
  if (options.lifecycle?.isShuttingDown)
2173
2552
  throw new Error("Cannot start HTTP during shutdown.");
2174
2553
  let abortedDuringShutdown = 0;
2175
- const onRequest = (request, server) => {
2554
+ const validate = (request, _server) => {
2176
2555
  if (options.lifecycle?.isShuttingDown)
2177
2556
  return new Response("Service Unavailable", { status: 503 });
2178
2557
  if (!URL.canParse(request.url))
@@ -2186,16 +2565,28 @@ function createWebServer(options) {
2186
2565
  abortedDuringShutdown++;
2187
2566
  }, { once: true });
2188
2567
  }
2189
- return options.onRequest?.(request, server);
2190
2568
  };
2569
+ const onRequest = options.onRequest;
2191
2570
  for (const field of ["fetch", "routes", "port", "unix"])
2192
2571
  if (options.native && field in options.native)
2193
2572
  throw new TypeError(`native.${field} is owned by createWebServer.`);
2194
- const maxRequestBodySize = options.native?.maxRequestBodySize ?? resolveMaxBodyBytes();
2573
+ const responsePolicy = resolveHttpResponsePolicy(Object.freeze({ ...options.env ?? process.env }));
2574
+ if (options.cors)
2575
+ resolveCorsConfig3(options.cors);
2576
+ const cors = {
2577
+ ...responsePolicy.cors,
2578
+ ...options.cors,
2579
+ additionalAllowedHeaders: [
2580
+ ...responsePolicy.cors?.additionalAllowedHeaders ?? [],
2581
+ ...options.cors?.additionalAllowedHeaders ?? []
2582
+ ]
2583
+ };
2584
+ const maxRequestBodySize = options.native?.maxRequestBodySize ?? responsePolicy.maxBodyBytes ?? resolveMaxBodyBytes2();
2195
2585
  if (!Number.isSafeInteger(maxRequestBodySize) || maxRequestBodySize <= 0)
2196
2586
  throw new RangeError("maxRequestBodySize must be a positive safe integer.");
2587
+ const renderError = options.errorView;
2197
2588
  const active = new Set;
2198
- const track = (work) => {
2589
+ const trackOwned = (work) => {
2199
2590
  if (!options.lifecycle)
2200
2591
  return work();
2201
2592
  const running = work();
@@ -2204,8 +2595,9 @@ function createWebServer(options) {
2204
2595
  active.delete(running);
2205
2596
  });
2206
2597
  };
2207
- const publicDir = options.publicDir ?? "./public";
2208
- const bunRoutes = options.routes ? convertAppRoutesToBunRoutes(options.routes, options.cors, onRequest, track) : undefined;
2598
+ const track = (work) => trackOwned(async () => await runWithRequestMeta({ ...currentRequestMeta2(), webErrorView: renderError }, work));
2599
+ const publicDir = resolve5(options.publicDir ?? "./public");
2600
+ const bunRoutes = options.routes ? convertAppRoutesToBunRoutes(options.routes, cors, onRequest, track, options.enter, validate) : undefined;
2209
2601
  const { websocket, ...native } = options.native ?? {};
2210
2602
  const configuration = {
2211
2603
  ...native,
@@ -2220,11 +2612,16 @@ function createWebServer(options) {
2220
2612
  peerAddress: socketAddress(server, request),
2221
2613
  userAgent: request.headers.get("user-agent")
2222
2614
  }, async () => {
2223
- const intercepted = await onRequest(request, server);
2224
- if (intercepted instanceof Response)
2225
- return intercepted;
2615
+ const invalid = validate(request, server);
2616
+ if (invalid)
2617
+ return invalid;
2226
2618
  const url = new URL(request.url);
2619
+ let assetAdmission = false;
2227
2620
  if (url.pathname.startsWith("/assets/")) {
2621
+ const intercepted = await onRequest?.(request, server);
2622
+ if (intercepted instanceof Response)
2623
+ return intercepted;
2624
+ assetAdmission = true;
2228
2625
  try {
2229
2626
  const filePath = assertUrlPathUnderRoot2(publicDir, url.pathname);
2230
2627
  const file = Bun.file(filePath);
@@ -2236,7 +2633,24 @@ function createWebServer(options) {
2236
2633
  }
2237
2634
  }
2238
2635
  if (options.handle) {
2239
- const response = await options.handle(request, server);
2636
+ const owned = await dispatchOwnedRoute(options.handle, request, (ports) => assetAdmission ? undefined : onRequest?.(request, server, ports));
2637
+ if (owned)
2638
+ return owned;
2639
+ if (websocket && !options.enter) {
2640
+ const intercepted = assetAdmission ? undefined : await onRequest?.(request, server);
2641
+ if (intercepted instanceof Response)
2642
+ return intercepted;
2643
+ return await options.handle(request, server) ?? undefined;
2644
+ }
2645
+ const work = async (_request, ports) => {
2646
+ const intercepted = assetAdmission ? undefined : await onRequest?.(request, server, ports);
2647
+ if (intercepted instanceof Response)
2648
+ return intercepted;
2649
+ return await options.handle?.(request, server, ports) ?? await missingHtmlResponse();
2650
+ };
2651
+ if (options.enter)
2652
+ return options.enter(request, work);
2653
+ const response = await work(request);
2240
2654
  if (response === undefined && websocket)
2241
2655
  return;
2242
2656
  return response ?? await missingHtmlResponse();
@@ -2245,12 +2659,22 @@ function createWebServer(options) {
2245
2659
  }));
2246
2660
  }
2247
2661
  };
2248
- const server = websocket ? Bun.serve({ ...configuration, websocket }) : Bun.serve({
2662
+ const nativeOptions = websocket ? { ...configuration, websocket } : {
2249
2663
  ...configuration,
2250
2664
  async fetch(request, server) {
2251
2665
  return await configuration.fetch(request, server) ?? await missingHtmlResponse();
2252
2666
  }
2253
- });
2667
+ };
2668
+ const provenScalarOptions = typeof configuration.port === "number" && Number.isSafeInteger(configuration.port) && configuration.port >= 0 && configuration.port <= 65535 && websocket === undefined && scalarNativeOptions(native);
2669
+ let server;
2670
+ try {
2671
+ server = Bun.serve(nativeOptions);
2672
+ } catch (error) {
2673
+ if (provenScalarOptions && isNativeListenConflict(error))
2674
+ ownership?.bindRejected();
2675
+ throw error;
2676
+ }
2677
+ ownership?.acquired(server);
2254
2678
  if (options.lifecycle) {
2255
2679
  const lifecycle = options.lifecycle;
2256
2680
  const name = `http:${crypto.randomUUID()}`;
@@ -2270,56 +2694,56 @@ function createWebServer(options) {
2270
2694
  }
2271
2695
  return server;
2272
2696
  }
2697
+ function scalarNativeOptions(options) {
2698
+ try {
2699
+ for (const key of Reflect.ownKeys(options)) {
2700
+ const descriptor = Object.getOwnPropertyDescriptor(options, key);
2701
+ if (!descriptor || !("value" in descriptor))
2702
+ return false;
2703
+ const value = descriptor.value;
2704
+ if (value !== null && value !== undefined && !["string", "number", "boolean"].includes(typeof value))
2705
+ return false;
2706
+ }
2707
+ return true;
2708
+ } catch {
2709
+ return false;
2710
+ }
2711
+ }
2712
+ function isNativeListenConflict(error) {
2713
+ if (!error || typeof error !== "object")
2714
+ return false;
2715
+ try {
2716
+ const code = Object.getOwnPropertyDescriptor(error, "code");
2717
+ const syscall = Object.getOwnPropertyDescriptor(error, "syscall");
2718
+ return code !== undefined && "value" in code && code.value === "EADDRINUSE" && syscall !== undefined && "value" in syscall && syscall.value === "listen";
2719
+ } catch {
2720
+ return false;
2721
+ }
2722
+ }
2273
2723
  // ../../src/bootstrap/web/session.ts
2274
2724
  import { createHmac, randomBytes } from "crypto";
2275
2725
  import { isAccountActive, matchesAuthVersion } from "@getstrata/core/auth/accountState";
2276
- import { AuthManager as AuthManager2 } from "@getstrata/core/auth/guard";
2277
- import { isSessionInvalidated } from "@getstrata/core/auth/sessionCookie";
2278
- import { getBoundDatabaseConnection as getBoundDatabaseConnection2 } from "@getstrata/core/database/boundConnection";
2279
- import {
2280
- getActiveDatabaseConnection,
2281
- hasActiveDatabaseConnection
2282
- } from "@getstrata/core/database/connectionContext";
2283
2726
  import {
2284
- getDefaultDatabasePool as getDefaultDatabasePool3,
2285
- getDefaultDatabaseQuery
2286
- } from "@getstrata/core/database/defaultConnection";
2287
- import { currentSqlDialect, sqlTimestamp } from "@getstrata/core/database/dialect";
2727
+ AuthManager as AuthManager2,
2728
+ authenticateProof,
2729
+ authUserFromOutcome
2730
+ } from "@getstrata/core/auth/guard";
2731
+ import { isSessionInvalidated } from "@getstrata/core/auth/sessionCookie";
2288
2732
  import { UnauthorizedError } from "@getstrata/core/errors/http";
2289
2733
  import { readRequestCookie } from "@getstrata/core/http/cookies";
2290
2734
  import { currentRequestMeta as currentRequestMeta3 } from "@getstrata/core/http/requestMetaContext";
2291
- import { isProductionEnv as isProductionEnv3 } from "@getstrata/core/runtime/appEnv";
2292
2735
  import { timingSafeCompareString } from "@getstrata/core/security/timingSafeCompare";
2293
- import { runWithMigrationBypassForIdentifier } from "@getstrata/core/tenant/databaseTenantContext";
2294
- function sqlPlaceholder(index) {
2295
- return currentSqlDialect().placeholder(index);
2736
+ function sqlPlaceholder(sql, index) {
2737
+ return sql.dialect.placeholder(index);
2296
2738
  }
2297
- function sqlNow() {
2298
- return currentSqlDialect().nowExpression();
2739
+ function sqlNow(sql) {
2740
+ return sql.dialect.nowExpression();
2299
2741
  }
2300
- function isSqlClient(value) {
2301
- return typeof value.unsafe === "function";
2302
- }
2303
- function resolveSql(source) {
2304
- const client = isSqlClient(source) ? source : source();
2305
- if (!hasActiveDatabaseConnection()) {
2306
- return client;
2307
- }
2308
- try {
2309
- if (client === getDefaultDatabasePool3() || client === getDefaultDatabaseQuery()) {
2310
- return getActiveDatabaseConnection(client);
2311
- }
2312
- } catch {
2313
- return client;
2314
- }
2315
- return client;
2742
+ function executeSql(sql, text, params = []) {
2743
+ return sql.execute({ text, params });
2316
2744
  }
2317
- function defaultSessionSql() {
2318
- const bound = getBoundDatabaseConnection2();
2319
- if (bound) {
2320
- return bound;
2321
- }
2322
- return getDefaultDatabasePool3();
2745
+ function identifier(sql, policy, productionRls, id, work) {
2746
+ return productionRls ? policy.run(sql, { kind: "identifier", identifier: id }, work) : Promise.resolve(work(sql));
2323
2747
  }
2324
2748
  function defaultMapSessionUser(user) {
2325
2749
  return {
@@ -2351,11 +2775,11 @@ function mapSessionUserRow(row) {
2351
2775
  ...row.email_verified_at !== undefined ? { email_verified_at: row.email_verified_at } : {}
2352
2776
  };
2353
2777
  }
2354
- async function defaultLoadSessionUser(sql, sessionId) {
2355
- const sessionRows = await runWithMigrationBypassForIdentifier(sessionId, async () => {
2356
- return await sql.unsafe(`SELECT *, created_at AS session_created_at
2778
+ async function defaultLoadSessionUser(sql, policy, rls, sessionId) {
2779
+ const sessionRows = await identifier(sql, policy, rls, sessionId, async (sql) => {
2780
+ return await executeSql(sql, `SELECT *, created_at AS session_created_at
2357
2781
  FROM sessions
2358
- WHERE id = ${sqlPlaceholder(1)} AND expires_at > ${sqlNow()}`, [sessionId]);
2782
+ WHERE id = ${sqlPlaceholder(sql, 1)} AND expires_at > ${sqlNow(sql)}`, [sessionId]);
2359
2783
  });
2360
2784
  const session = sessionRows[0];
2361
2785
  if (!session)
@@ -2364,10 +2788,8 @@ async function defaultLoadSessionUser(sql, sessionId) {
2364
2788
  if (!Number.isInteger(userId) || userId <= 0) {
2365
2789
  return null;
2366
2790
  }
2367
- return await runWithMigrationBypassForIdentifier(userId, async () => {
2368
- const rows = await sql.unsafe(`SELECT * FROM users WHERE id = ${sqlPlaceholder(1)}`, [
2369
- userId
2370
- ]);
2791
+ return await identifier(sql, policy, rls, userId, async (sql) => {
2792
+ const rows = await executeSql(sql, `SELECT * FROM users WHERE id = ${sqlPlaceholder(sql, 1)}`, [userId]);
2371
2793
  const row = rows[0];
2372
2794
  if (!row)
2373
2795
  return null;
@@ -2390,14 +2812,18 @@ function redirectWithCookie(location, setCookie, status) {
2390
2812
  }
2391
2813
 
2392
2814
  class CookieSessionStore {
2393
- sqlSource;
2815
+ selected;
2816
+ policy;
2394
2817
  secret;
2818
+ config;
2395
2819
  cookieName;
2396
2820
  maxAgeSeconds;
2397
2821
  loadSessionUser;
2398
- constructor(sqlSource, secret, cookieName = "strata_session", maxAgeSeconds = 60 * 60 * 24 * 14, loadSessionUser = defaultLoadSessionUser) {
2399
- this.sqlSource = sqlSource;
2822
+ constructor(selected, policy, secret, config, cookieName = "strata_session", maxAgeSeconds = 60 * 60 * 24 * 14, loadSessionUser = defaultLoadSessionUser) {
2823
+ this.selected = selected;
2824
+ this.policy = policy;
2400
2825
  this.secret = secret;
2826
+ this.config = config;
2401
2827
  this.cookieName = cookieName;
2402
2828
  this.maxAgeSeconds = maxAgeSeconds;
2403
2829
  this.loadSessionUser = loadSessionUser;
@@ -2409,6 +2835,12 @@ class CookieSessionStore {
2409
2835
  clearCookieHeader() {
2410
2836
  return this.withSecureFlag(`${this.cookieName}=; Path=/; HttpOnly; SameSite=Lax; Max-Age=0`);
2411
2837
  }
2838
+ hasCredential(request) {
2839
+ return readRequestCookie(request, this.cookieName) !== null || (request.headers.get("cookie")?.split(";").some((part) => {
2840
+ const separator = part.indexOf("=");
2841
+ return (separator === -1 ? part : part.slice(0, separator)).trim() === this.cookieName;
2842
+ }) ?? false);
2843
+ }
2412
2844
  sessionIdFromRequest(request) {
2413
2845
  const cookie = readRequestCookie(request, this.cookieName);
2414
2846
  const raw = cookie ?? null;
@@ -2421,25 +2853,22 @@ class CookieSessionStore {
2421
2853
  return sessionId;
2422
2854
  }
2423
2855
  withSecureFlag(header) {
2424
- if (!isProductionEnv3()) {
2856
+ if (!this.config.production) {
2425
2857
  return header;
2426
2858
  }
2427
2859
  return header.includes("Secure") ? header : `${header}; Secure`;
2428
2860
  }
2429
- sql() {
2430
- return resolveSql(this.sqlSource);
2431
- }
2432
2861
  async create(user, meta = {}) {
2433
2862
  if (!isAccountActive(user) || !matchesAuthVersion(user.auth_version, user.auth_version))
2434
2863
  throw new UnauthorizedError;
2435
2864
  const id = randomBytes(32).toString("hex");
2436
2865
  const expires = new Date(Date.now() + this.maxAgeSeconds * 1000);
2437
- await runWithMigrationBypassForIdentifier(user.id, async () => {
2438
- await this.sql().unsafe(`INSERT INTO sessions (id, user_id, expires_at, user_agent, ip_address, last_active_at, created_at${user.auth_version !== undefined ? ", auth_version" : ""})
2439
- VALUES (${sqlPlaceholder(1)}, ${sqlPlaceholder(2)}, ${sqlPlaceholder(3)}, ${sqlPlaceholder(4)}, ${sqlPlaceholder(5)}, ${sqlNow()}, ${sqlNow()}${user.auth_version !== undefined ? `, ${sqlPlaceholder(6)}` : ""})`, [
2866
+ await identifier(this.selected, this.policy, this.config.rls, user.id, async (sql) => {
2867
+ await executeSql(sql, `INSERT INTO sessions (id, user_id, expires_at, user_agent, ip_address, last_active_at, created_at${user.auth_version !== undefined ? ", auth_version" : ""})
2868
+ VALUES (${sqlPlaceholder(sql, 1)}, ${sqlPlaceholder(sql, 2)}, ${sqlPlaceholder(sql, 3)}, ${sqlPlaceholder(sql, 4)}, ${sqlPlaceholder(sql, 5)}, ${sqlNow(sql)}, ${sqlNow(sql)}${user.auth_version !== undefined ? `, ${sqlPlaceholder(sql, 6)}` : ""})`, [
2440
2869
  id,
2441
2870
  user.id,
2442
- sqlTimestamp(expires),
2871
+ sql.dialect.timestampValue(expires),
2443
2872
  meta.userAgent ?? null,
2444
2873
  meta.ipAddress ?? null,
2445
2874
  ...user.auth_version !== undefined ? [user.auth_version] : []
@@ -2448,39 +2877,41 @@ class CookieSessionStore {
2448
2877
  return id;
2449
2878
  }
2450
2879
  async destroy(sessionId) {
2451
- await runWithMigrationBypassForIdentifier(sessionId, async () => {
2452
- await this.sql().unsafe(`DELETE FROM sessions WHERE id = ${sqlPlaceholder(1)}`, [sessionId]);
2880
+ await identifier(this.selected, this.policy, this.config.rls, sessionId, async (sql) => {
2881
+ await executeSql(sql, `DELETE FROM sessions WHERE id = ${sqlPlaceholder(sql, 1)}`, [
2882
+ sessionId
2883
+ ]);
2453
2884
  });
2454
2885
  }
2455
2886
  async destroyAllSessions(userId) {
2456
- await runWithMigrationBypassForIdentifier(userId, async () => {
2457
- await this.sql().unsafe(`DELETE FROM sessions WHERE user_id = ${sqlPlaceholder(1)}`, [
2887
+ await identifier(this.selected, this.policy, this.config.rls, userId, async (sql) => {
2888
+ await executeSql(sql, `DELETE FROM sessions WHERE user_id = ${sqlPlaceholder(sql, 1)}`, [
2458
2889
  userId
2459
2890
  ]);
2460
2891
  });
2461
2892
  }
2462
2893
  async destroyOtherSessions(userId, keepSessionId) {
2463
- await runWithMigrationBypassForIdentifier(userId, async () => {
2464
- await this.sql().unsafe(`DELETE FROM sessions WHERE user_id = ${sqlPlaceholder(1)} AND id <> ${sqlPlaceholder(2)}`, [userId, keepSessionId]);
2894
+ await identifier(this.selected, this.policy, this.config.rls, userId, async (sql) => {
2895
+ await executeSql(sql, `DELETE FROM sessions WHERE user_id = ${sqlPlaceholder(sql, 1)} AND id <> ${sqlPlaceholder(sql, 2)}`, [userId, keepSessionId]);
2465
2896
  });
2466
2897
  }
2467
2898
  async listForUser(userId) {
2468
- const dialect = currentSqlDialect();
2469
- return await runWithMigrationBypassForIdentifier(userId, () => this.sql().unsafe(`SELECT id, user_id, user_agent, ip_address, last_active_at, expires_at
2899
+ const dialect = this.selected.dialect;
2900
+ return await identifier(this.selected, this.policy, this.config.rls, userId, (sql) => executeSql(sql, `SELECT id, user_id, user_agent, ip_address, last_active_at, expires_at
2470
2901
  FROM sessions
2471
2902
  WHERE user_id = ${dialect.placeholder(1)} AND expires_at > ${dialect.nowExpression()}
2472
2903
  ORDER BY last_active_at DESC${dialect.nullsLastSuffix()}, expires_at DESC`, [userId]));
2473
2904
  }
2474
2905
  async touch(sessionId) {
2475
- await runWithMigrationBypassForIdentifier(sessionId, async () => {
2476
- await this.sql().unsafe(`UPDATE sessions SET last_active_at = ${sqlNow()} WHERE id = ${sqlPlaceholder(1)}`, [sessionId]);
2906
+ await identifier(this.selected, this.policy, this.config.rls, sessionId, async (sql) => {
2907
+ await executeSql(sql, `UPDATE sessions SET last_active_at = ${sqlNow(sql)} WHERE id = ${sqlPlaceholder(sql, 1)}`, [sessionId]);
2477
2908
  });
2478
2909
  }
2479
2910
  async read(request) {
2480
2911
  const sessionId = this.sessionIdFromRequest(request);
2481
2912
  if (!sessionId)
2482
2913
  return null;
2483
- const user = await this.loadSessionUser(this.sql(), sessionId);
2914
+ const user = await this.loadSessionUser(this.selected, this.policy, this.config.rls, sessionId);
2484
2915
  return user && isAccountActive(user) ? user : null;
2485
2916
  }
2486
2917
  sign(value) {
@@ -2495,7 +2926,13 @@ class CookieSessionGuard {
2495
2926
  this.store = store;
2496
2927
  this.mapUser = mapUser;
2497
2928
  }
2929
+ authenticate(request) {
2930
+ return authenticateProof("session", () => this.store.hasCredential(request), () => this.resolveUser(request));
2931
+ }
2498
2932
  async resolve(request) {
2933
+ return authUserFromOutcome(await this.authenticate(request));
2934
+ }
2935
+ async resolveUser(request) {
2499
2936
  const user = await this.store.read(request);
2500
2937
  if (!user) {
2501
2938
  return null;
@@ -2537,8 +2974,10 @@ class CookieSessionAuthManager extends AuthManager2 {
2537
2974
  return redirectWithCookie(location, setCookie, status);
2538
2975
  }
2539
2976
  }
2540
- function createCookieSessionAuthManager(options = {}) {
2541
- const store = options.store ?? new CookieSessionStore(options.sql ?? defaultSessionSql, options.secret ?? process.env.SESSION_SECRET?.trim() ?? "", options.cookieName, options.maxAgeSeconds, options.loadSessionUser);
2977
+ function createCookieSessionAuthManager(options) {
2978
+ if (!options.secret)
2979
+ throw new TypeError("An explicit session secret is required.");
2980
+ const store = new CookieSessionStore(options.selected, options.policy, options.secret, { production: options.production, rls: options.rls }, options.cookieName, options.maxAgeSeconds, options.loadSessionUser);
2542
2981
  return new CookieSessionAuthManager(store, options.mapUser ?? defaultMapSessionUser);
2543
2982
  }
2544
2983
  // ../../src/bootstrap/web/slug.ts
@@ -2553,9 +2992,10 @@ export {
2553
2992
  CORE_CACHE_TOKEN,
2554
2993
  CORE_CONFIG_TOKEN,
2555
2994
  CORE_EVENT_BUS_TOKEN,
2995
+ CORE_MAIL_TOKEN,
2556
2996
  CORE_POLICY_GATE_TOKEN,
2557
2997
  CORE_QUEUE_TOKEN,
2558
- CORE_TOKEN_SERVICE_TOKEN,
2998
+ CORE_STORAGE_TOKEN,
2559
2999
  CSRF_TARGET_ORIGIN_CONFIG_KEY,
2560
3000
  CookieSessionAuthManager,
2561
3001
  CookieSessionGuard,
@@ -2564,7 +3004,6 @@ export {
2564
3004
  DEFAULT_APP_PORT,
2565
3005
  REDIS_URL_CONFIG_KEY,
2566
3006
  RedisSchedulerLeaseStore,
2567
- RouteRegistry,
2568
3007
  Schedule,
2569
3008
  SchedulerLeaseLostError,
2570
3009
  ServiceContainer,
@@ -2577,52 +3016,48 @@ export {
2577
3016
  checkDatabase,
2578
3017
  checkRedis,
2579
3018
  collectProviders,
2580
- configureModulesDirectory,
2581
- configureModulesManifest,
2582
- coreProviders,
3019
+ compileRouteMap,
3020
+ composeRouteMaps,
2583
3021
  createAppContext,
2584
3022
  createAppDependencies,
3023
+ createCacheBindings,
3024
+ createCachedJson,
2585
3025
  createCookieSessionAuthManager,
3026
+ createCoreProviders,
2586
3027
  createCsrfProtection,
2587
3028
  createHealthRoutes,
2588
3029
  createHttpKernel,
3030
+ createMailBindings,
2589
3031
  createMetricsRoutes,
2590
3032
  createMetricsRuntime,
3033
+ createModuleDiscovery,
2591
3034
  createRouteKernel,
3035
+ createStorageBindings,
3036
+ createStorageProvider,
3037
+ createTracingProvider,
2592
3038
  createWebRoutes,
2593
3039
  createWebServer,
2594
3040
  discoverJobs,
2595
3041
  discoverModelTableNames,
2596
3042
  discoverModels,
2597
- discoverModules,
2598
3043
  ensureModulesLoaded,
2599
3044
  getRequiredDependency,
3045
+ getRouteInventory,
2600
3046
  mergeWebRoutes,
2601
3047
  parseFormBody,
2602
3048
  pingDatabase,
2603
3049
  prefixRouteMap,
2604
3050
  registerDefaultJobs,
2605
3051
  resetDiscoverJobsForTests,
2606
- resolveApplicationAuth,
2607
- resolveApplicationCache,
2608
- resolveApplicationConfig,
2609
- resolveApplicationDependencies,
2610
- resolveApplicationEventBus,
2611
- resolveApplicationLogger,
2612
- resolveApplicationPolicyGate,
2613
- resolveApplicationQueue,
2614
3052
  resolveMembershipService,
2615
3053
  resolveService,
2616
3054
  routeParams,
2617
- routeRegistry,
2618
3055
  runDueScheduledTasks,
2619
3056
  runProviderPhase,
2620
3057
  securedBindRouteModel,
2621
3058
  securedBindRouteModelByKey,
2622
- setActiveApplicationContext,
2623
3059
  slugify,
2624
3060
  toRouteRequest,
2625
- tracing_default as tracingProvider,
2626
3061
  wrapSecuredRouteModelByKey,
2627
3062
  wrapWebLogin,
2628
3063
  wrapWebRegister