@getstrata/bootstrap 2.2.60 → 3.0.5

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 +35 -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
@@ -1,20 +1,7 @@
1
1
  // @bun
2
2
  // ../../src/bootstrap/context.ts
3
3
  import { CORE_HTTP_CLEANUP_TOKEN as CORE_HTTP_CLEANUP_TOKEN2 } from "@getstrata/core/contracts/serviceTokens";
4
- import { clearActiveApplicationContext } from "@getstrata/core/runtime/applicationRegistry";
5
-
6
- // ../../src/bootstrap/applicationRegistry.ts
7
- import {
8
- resolveApplicationAuth,
9
- resolveApplicationCache,
10
- resolveApplicationConfig,
11
- resolveApplicationDependencies,
12
- resolveApplicationEventBus,
13
- resolveApplicationLogger,
14
- resolveApplicationPolicyGate,
15
- resolveApplicationQueue,
16
- setActiveApplicationContext
17
- } from "@getstrata/core/runtime/applicationRegistry";
4
+ import { createApplication } from "@getstrata/core/runtime/application";
18
5
 
19
6
  // ../../src/bootstrap/contracts.ts
20
7
  import {
@@ -28,200 +15,185 @@ import {
28
15
  resolveService
29
16
  } from "@getstrata/core/contracts/di";
30
17
 
31
- // ../../src/bootstrap/discoverModules.ts
32
- import { readdir as readdir2 } from "fs/promises";
33
- import { join as join2, resolve } from "path";
34
-
35
- // ../../src/bootstrap/infrastructureDiscovery.ts
36
- import { readdir } from "fs/promises";
37
- import { join, relative } from "path";
38
- import { pathToFileURL } from "url";
39
- async function infrastructureFiles(directory, exclude = []) {
40
- const excluded = new Set([
41
- "index.ts",
42
- "index.js",
43
- "index.mts",
44
- "index.mjs",
45
- "register.ts",
46
- "register.js",
47
- "register.mts",
48
- "register.mjs",
49
- ...exclude
50
- ]);
51
- const files = [];
52
- async function visit(path) {
53
- const entries = await readdir(path, { withFileTypes: true });
54
- entries.sort((a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0);
55
- for (const entry of entries) {
56
- const file = join(path, entry.name);
57
- const key = relative(directory, file).replaceAll("\\", "/");
58
- if (excluded.has(entry.name) || excluded.has(key))
59
- continue;
60
- if (entry.isDirectory())
61
- await visit(file);
62
- else if (entry.isFile() && /\.(ts|js|mts|mjs)$/.test(entry.name) && !/\.(d|test|spec)\.[cm]?[jt]s$/.test(entry.name))
63
- files.push(file);
64
- }
65
- }
66
- try {
67
- await visit(directory);
68
- } catch (error) {
69
- if (error.code !== "ENOENT")
70
- throw error;
71
- if (error.path !== directory)
72
- throw error;
73
- }
74
- return files;
75
- }
76
- async function importInfrastructure(file) {
77
- try {
78
- return await import(pathToFileURL(file).href);
79
- } catch (error) {
80
- throw new Error(`Cannot load infrastructure module ${file}`, { cause: error });
81
- }
82
- }
83
-
84
- // ../../src/bootstrap/discoverModules.ts
85
- var KEY = Symbol.for("@getstrata/discoverModulesState");
86
- function state() {
87
- const globals = globalThis;
88
- globals[KEY] ??= { appModules: [] };
89
- return globals[KEY];
90
- }
91
- function configureModulesDirectory(modulesDir) {
92
- const current = state();
93
- const directory = resolve(modulesDir);
94
- if (current.configuredModulesDir !== directory || current.configuredManifest) {
95
- current.appModules.length = 0;
96
- current.modulesReady = undefined;
97
- current.source = undefined;
98
- }
99
- current.configuredManifest = undefined;
100
- current.configuredModulesDir = directory;
101
- }
102
- function configureModulesManifest(manifest) {
103
- const current = state();
104
- if (current.configuredManifest !== manifest) {
105
- current.appModules.length = 0;
106
- current.modulesReady = undefined;
107
- current.source = undefined;
108
- }
109
- current.configuredManifest = manifest;
18
+ // ../../src/bootstrap/httpPersistence.ts
19
+ import { establishedAuthReader, runWithEstablishedAuth } from "@getstrata/core/auth/authReader";
20
+ import { validatedAuthOutcome } from "@getstrata/core/auth/guard";
21
+ import { runWithMembershipSnapshot } from "@getstrata/core/auth/membershipContext";
22
+ import { InternalServerError, InvalidCredentialsError } from "@getstrata/core/errors/http";
23
+ import { currentRequestMeta } from "@getstrata/core/http/requestMetaContext";
24
+ import { errorResponse } from "@getstrata/core/http/response";
25
+ import { webErrorResponse } from "@getstrata/core/http/webErrorResponse";
26
+ import { createPublicTenantSelector } from "@getstrata/core/tenant/publicTenantHost";
27
+ import { runWithTenant } from "@getstrata/core/tenant/tenantContext";
28
+ import { DEFAULT_TENANT, resolveTenantForRequest } from "@getstrata/core/tenant/tenantMiddleware";
29
+ import { businessPorts } from "#strata-http-route";
30
+ import { HTTP_PERSISTENCE_OPTIONS } from "#strata-http-route";
31
+ function snapshotAuth(input) {
32
+ const auth = validatedAuthOutcome(input);
33
+ if (auth.status === "error")
34
+ throw Object.assign(new InternalServerError, { cause: auth.error });
35
+ if (auth.status === "invalid")
36
+ throw new InvalidCredentialsError;
37
+ const user = auth.user;
38
+ const name = user?.name;
39
+ const email = user?.email;
40
+ return Object.freeze({
41
+ credentialSource: auth.credentialSource,
42
+ user: user ? Object.freeze({
43
+ id: user.id,
44
+ ...typeof name === "string" ? { name } : {},
45
+ ...typeof email === "string" ? { email } : {},
46
+ ...user.role !== undefined ? { role: user.role } : {},
47
+ ...user.isActive !== undefined ? { isActive: user.isActive } : {},
48
+ ...user.authVersion !== undefined ? { authVersion: user.authVersion } : {},
49
+ ...user.tokenId !== undefined ? { tokenId: user.tokenId } : {},
50
+ ...user.abilities ? { abilities: Object.freeze([...user.abilities]) } : {},
51
+ ...user.emailVerifiedAt !== undefined ? {
52
+ emailVerifiedAt: user.emailVerifiedAt instanceof Date ? user.emailVerifiedAt.toISOString() : user.emailVerifiedAt
53
+ } : {}
54
+ }) : null
55
+ });
110
56
  }
111
- function validateModule(value, location) {
112
- if (!value || typeof value !== "object" || Array.isArray(value))
113
- throw new TypeError(`Invalid application module at ${location}.`);
114
- const module = value;
115
- if (typeof module.name !== "string" || !module.name.trim())
116
- throw new TypeError(`Invalid module name at ${location}.`);
117
- if (module.order !== undefined && (typeof module.order !== "number" || !Number.isFinite(module.order)))
118
- throw new TypeError(`Invalid module order at ${location}.`);
119
- for (const hook of ["routes", "webRoutes"])
120
- if (module[hook] !== undefined && typeof module[hook] !== "function")
121
- throw new TypeError(`Invalid ${hook} at ${location}.`);
122
- if (module.providers !== undefined) {
123
- if (!Array.isArray(module.providers))
124
- throw new TypeError(`Invalid providers at ${location}.`);
125
- for (const provider of module.providers) {
126
- if (!provider || typeof provider.name !== "string" || !provider.name.trim() || provider.register !== undefined && typeof provider.register !== "function" || provider.boot !== undefined && typeof provider.boot !== "function")
127
- throw new TypeError(`Invalid provider at ${location}.`);
128
- }
129
- }
57
+ function snapshotTenant(tenant) {
58
+ const snapshot = structuredClone(tenant);
59
+ if (!snapshot || typeof snapshot !== "object" || Array.isArray(snapshot) || !Number.isSafeInteger(snapshot.id) || snapshot.id < 1 || typeof snapshot.slug !== "string")
60
+ throw new TypeError("HTTP metadata must establish a valid tenant identity.");
61
+ return Object.freeze(snapshot);
130
62
  }
131
- async function load(options) {
132
- const manifest = options.manifest ?? (options.modulesDir === undefined ? state().configuredManifest : undefined);
133
- const entries = [];
134
- if (manifest)
135
- for (const [index, value] of manifest.entries())
136
- entries.push({ value, location: `module manifest[${index}]` });
137
- else {
138
- const directory = options.modulesDir ?? state().configuredModulesDir;
139
- if (!directory)
140
- throw new Error("configureModulesDirectory() or configureModulesManifest() must be called before discovering modules.");
141
- let folders;
142
- try {
143
- folders = await readdir2(directory, { withFileTypes: true });
144
- } catch (error) {
145
- if (error.code === "ENOENT")
146
- return [];
147
- throw error;
148
- }
149
- const excluded = new Set(options.exclude ?? []);
150
- 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)) {
151
- const path = join2(directory, folder.name);
152
- const files = await readdir2(path);
153
- const candidates = files.filter((file) => /^index\.(ts|js|mts|mjs)$/.test(file));
154
- if (candidates.length !== 1)
155
- throw new Error(`Expected one module entrypoint at ${path}; found ${candidates.length}.`);
156
- const file = join2(path, candidates[0]);
157
- const exports = await importInfrastructure(file);
158
- entries.push({ value: exports.default, location: file });
63
+ function createHttpPersistence(invoke, options) {
64
+ const invalidSessionCookie = options.invalidSessionCookie ? Object.freeze({ ...options.invalidSessionCookie }) : undefined;
65
+ const selectPublic = options.publicTenancy ? createPublicTenantSelector(options.publicTenancy) : undefined;
66
+ return async (request, handler, identity, scim = false) => {
67
+ const externalId = currentRequestMeta().requestId;
68
+ const metadata = { routeTemplate: currentRequestMeta().routeTemplate ?? "", phase: "metadata" };
69
+ const established = await invoke({
70
+ kind: "request",
71
+ externalId,
72
+ signal: request.signal,
73
+ metadata,
74
+ actor: { kind: "system", policy: "http.identity-metadata" }
75
+ }, async (ports) => {
76
+ if (scim) {
77
+ if (!options.scim)
78
+ throw new Error("Explicit SCIM metadata authentication is required.");
79
+ const tenant = await options.scim(request, ports.database);
80
+ if (tenant instanceof Response)
81
+ return tenant;
82
+ return Object.freeze({
83
+ auth: Object.freeze({ user: null, credentialSource: "bearer" }),
84
+ memberships: Object.freeze([]),
85
+ tenant: snapshotTenant(tenant)
86
+ });
87
+ }
88
+ const lookup = options.metadata(ports);
89
+ const outcome = validatedAuthOutcome(await lookup.authenticate(request));
90
+ if (outcome.status === "invalid" && outcome.credentialSource === "session" && invalidSessionCookie && request.headers.get("cookie")?.split(";").some((part) => part.trim().startsWith(`${invalidSessionCookie.name}=`))) {
91
+ const error = new InvalidCredentialsError;
92
+ const response = await webErrorResponse(error, request) ?? errorResponse(error);
93
+ response.headers.append("Set-Cookie", invalidSessionCookie.expiredHeader);
94
+ return response;
95
+ }
96
+ const auth = snapshotAuth(outcome);
97
+ const memberships = auth.user ? await lookup.memberships(auth.user) : [];
98
+ const resolveTenant = async (id) => {
99
+ const result = await lookup.tenant(id);
100
+ if (result === null)
101
+ return null;
102
+ const snapshot = snapshotTenant(result);
103
+ if (snapshot.id !== id)
104
+ throw new Error("Tenant resolver returned a different tenant identity.");
105
+ return snapshot;
106
+ };
107
+ const tenant = options.tenancy === "none" ? snapshotTenant(DEFAULT_TENANT) : await resolveTenantForRequest(request, {
108
+ auth,
109
+ config: {
110
+ enabled: true,
111
+ production: options.production,
112
+ allowDevHeaders: options.allowTenantDevHeaders
113
+ },
114
+ resolveTenant,
115
+ userTenantId: lookup.userTenantId
116
+ }, resolveTenant, selectPublic);
117
+ return Object.freeze({
118
+ auth,
119
+ tenant,
120
+ memberships: Object.freeze(memberships.map((row) => Object.freeze({ ...row })))
121
+ });
122
+ });
123
+ if (established instanceof Response)
124
+ return established;
125
+ const claims = {};
126
+ if (established.auth.user) {
127
+ for (const [key, value] of Object.entries(established.auth.user))
128
+ if (value !== undefined) {
129
+ if (value === null || typeof value === "string" || typeof value === "number" || typeof value === "boolean" || Array.isArray(value))
130
+ claims[key] = value;
131
+ }
159
132
  }
160
- }
161
- const names = new Map;
162
- const modules = [];
163
- for (const { value, location } of entries) {
164
- validateModule(value, location);
165
- const previous = names.get(value.name);
166
- if (previous)
167
- throw new Error(`Duplicate module "${value.name}" at ${location}; first declared at ${previous}.`);
168
- names.set(value.name, location);
169
- modules.push(value);
170
- }
171
- return modules.sort((left, right) => (left.order ?? 100) - (right.order ?? 100));
133
+ return invoke({
134
+ kind: "request",
135
+ externalId,
136
+ signal: request.signal,
137
+ metadata: {
138
+ ...metadata,
139
+ phase: identity ? "identity-operation" : "business",
140
+ credentialSource: established.auth.credentialSource
141
+ },
142
+ ...scim ? { actor: { kind: "system", policy: "http.scim" } } : identity ? { actor: { kind: "system", policy: "http.identity-operation" } } : established.auth.user ? { actor: { kind: "principal", claims } } : {},
143
+ tenant: { id: established.tenant.id, slug: established.tenant.slug }
144
+ }, (ports) => {
145
+ const policy = Object.freeze({
146
+ run: (selected, mode, work) => {
147
+ const allowed = mode.kind === "tenant" ? identity === undefined : identity?.includes(mode.kind) === true;
148
+ if (!allowed)
149
+ throw new Error("Database policy is not allowed by this route declaration.");
150
+ return ports.policy.run(selected, mode, work);
151
+ }
152
+ });
153
+ const work = (database) => runWithEstablishedAuth(request, established.auth, () => runWithMembershipSnapshot(established.memberships, () => {
154
+ const execute = () => handler(request, businessPorts({
155
+ database,
156
+ auth: establishedAuthReader,
157
+ established,
158
+ policy
159
+ }));
160
+ return runWithTenant(established.tenant, execute);
161
+ }));
162
+ return !identity && options.tenancy === "rls" ? ports.policy.run(ports.database, { kind: "tenant", tenantId: established.tenant.id }, work) : work(ports.database);
163
+ });
164
+ };
172
165
  }
173
- function ensureModulesLoaded(options = {}) {
174
- const current = state();
175
- const key = options.manifest ?? (options.modulesDir === undefined ? current.configuredManifest : undefined) ?? JSON.stringify([
176
- options.modulesDir ? resolve(options.modulesDir) : current.configuredModulesDir,
177
- [...options.exclude ?? []].sort()
178
- ]);
179
- if (current.modulesReady && current.source === key)
180
- return current.modulesReady;
181
- current.appModules.length = 0;
182
- current.source = key;
183
- const pending = load(options).then((modules) => {
184
- if (current.modulesReady !== pending)
185
- return modules;
186
- current.appModules.splice(0, current.appModules.length, ...modules);
187
- return current.appModules;
188
- }).catch((error) => {
189
- if (current.modulesReady === pending)
190
- current.modulesReady = undefined;
191
- throw error;
166
+
167
+ // ../../src/bootstrap/persistenceInvocation.ts
168
+ import { CORE_EXECUTION_OWNERSHIP_TOKEN } from "@getstrata/core/contracts/executionOwnership";
169
+ import { DATABASE_SESSION_TOKEN } from "@getstrata/core/database/tokens";
170
+ import { createScopedPolicy } from "@getstrata/core/tenant/scopedDatabasePolicy";
171
+ function createPersistenceInvocation(application, connection) {
172
+ if (!connection.trim())
173
+ throw new TypeError("A configured persistence connection is required.");
174
+ return (envelope, work) => application.run(envelope, (scope) => {
175
+ const database = scope.resolve(DATABASE_SESSION_TOKEN).connection(connection);
176
+ const policy = createScopedPolicy(scope.resolve(CORE_EXECUTION_OWNERSHIP_TOKEN), scope.context, database);
177
+ return work(Object.freeze({ database, policy }));
192
178
  });
193
- current.modulesReady = pending;
194
- return pending;
195
- }
196
- function discoverModules() {
197
- return state().appModules;
198
- }
199
- function resetDiscoverModulesForTests() {
200
- const current = state();
201
- current.configuredModulesDir = undefined;
202
- current.configuredManifest = undefined;
203
- current.appModules.length = 0;
204
- current.modulesReady = undefined;
205
- current.source = undefined;
206
179
  }
180
+
181
+ // ../../src/bootstrap/providers/index.ts
182
+ import { createStorageDriver as createStorageDriver2, resolveStorageConfig } from "@getstrata/core/storage/storage";
183
+
207
184
  // ../../src/bootstrap/providers/auth.ts
185
+ import { establishedAuthReader as establishedAuthReader2 } from "@getstrata/core/auth/authReader";
208
186
  import { BasicAuthGuard } from "@getstrata/core/auth/basicAuthGuard";
209
187
  import {
210
188
  AuthManager,
211
189
  CompositeGuard,
212
190
  DatabaseTokenGuard,
213
- GuestGuard
191
+ GuestGuard,
192
+ requireAuthCapability
214
193
  } from "@getstrata/core/auth/guard";
215
194
  import { JwtGuard } from "@getstrata/core/auth/jwtGuard";
216
195
  import { SessionGuard } from "@getstrata/core/auth/sessionGuard";
217
196
 
218
- // ../../src/config/auth.ts
219
- import { envFlagEnabled } from "@getstrata/core/runtime/appEnv";
220
- var authConfig = {
221
- allowDevHeaders: envFlagEnabled(process.env.AUTH_DEV_HEADERS),
222
- tokenDefaultAbilities: []
223
- };
224
-
225
197
  // ../../src/bootstrap/config.ts
226
198
  import {
227
199
  CORE_ABILITY_CHECKER_TOKEN,
@@ -235,8 +207,7 @@ import {
235
207
  CORE_PUBLIC_TENANCY_TOKEN,
236
208
  CORE_QUEUE_TOKEN,
237
209
  CORE_TENANT_RESOLVER_TOKEN,
238
- CORE_THROTTLE_QUOTA_POLICY_TOKEN,
239
- CORE_TOKEN_SERVICE_TOKEN
210
+ CORE_THROTTLE_QUOTA_POLICY_TOKEN
240
211
  } from "@getstrata/core/contracts/serviceTokens";
241
212
  var APP_PORT_CONFIG_KEY = "app.port";
242
213
  var CACHE_TTL_MS_CONFIG_KEY = "cache.ttlMs";
@@ -254,93 +225,139 @@ var DEFAULT_API_TOKEN = "";
254
225
  var DEFAULT_QUEUE_DRIVER = "sync";
255
226
 
256
227
  // ../../src/bootstrap/providers/auth.ts
228
+ function createMetadataAuthManager(directory, options, persistRecovery) {
229
+ const enabled = new Set(options.mechanisms);
230
+ if ([...enabled].some((name) => !["api", "jwt", "basic", "session"].includes(name)))
231
+ throw new TypeError("Unknown authentication mechanism.");
232
+ const named = new Map;
233
+ const guards = [];
234
+ const add = (name, guard) => {
235
+ named.set(name, guard);
236
+ guards.push(guard);
237
+ return guard;
238
+ };
239
+ if (enabled.has("api")) {
240
+ const api = add("api", new DatabaseTokenGuard(requireAuthCapability(directory, ["resolveUserFromToken"], "API token")));
241
+ named.set("access_token", api);
242
+ }
243
+ if (enabled.has("jwt")) {
244
+ if (!options.jwtSecret)
245
+ throw new TypeError("Explicit JWT secret is required.");
246
+ add("jwt", new JwtGuard({
247
+ directory: requireAuthCapability(directory, ["findByIdOrThrow"], "JWT"),
248
+ secret: options.jwtSecret
249
+ }));
250
+ }
251
+ if (enabled.has("basic")) {
252
+ const accounts = requireAuthCapability(directory, ["findByIdOrThrow"], "Basic account");
253
+ const emailLookup = directory.findByEmail === undefined ? undefined : requireAuthCapability(directory, ["findByEmail"], "Basic email lookup");
254
+ const credentials = directory.verifyCredentials === undefined ? undefined : requireAuthCapability(directory, ["verifyCredentials"], "Basic credentials");
255
+ let basic;
256
+ if (emailLookup)
257
+ basic = {
258
+ accounts,
259
+ emailLookup,
260
+ credentials,
261
+ persistRecovery,
262
+ mfaSecrets: options.mfaSecrets
263
+ };
264
+ else if (credentials)
265
+ basic = { accounts, credentials, persistRecovery, mfaSecrets: options.mfaSecrets };
266
+ else
267
+ throw new TypeError("Basic authentication requires an email lookup or credential verifier.");
268
+ add("basic", new BasicAuthGuard(basic));
269
+ }
270
+ if (enabled.has("session")) {
271
+ const session = add("web", options.sessionGuard !== undefined ? requireAuthCapability(options.sessionGuard, ["authenticate"], "custom session") : new SessionGuard(requireAuthCapability(directory, ["findByIdOrThrow"], "session account"), {
272
+ read: options.readSession,
273
+ hasCredential: requireAuthCapability(options, ["hasSessionCredential"], "session presence").hasSessionCredential,
274
+ abilities: options.roleAbilities,
275
+ validity: directory.hasActiveBrowserSession === undefined ? null : requireAuthCapability(directory, ["hasActiveBrowserSession"], "session validity")
276
+ }));
277
+ named.set("session", session);
278
+ }
279
+ if (!options.production && options.allowDevHeaders)
280
+ guards.push(new GuestGuard({ ...options, abilities: options.abilities }));
281
+ const auth = new AuthManager(new CompositeGuard(guards));
282
+ for (const [name, guard] of named)
283
+ auth.registerGuard(name, guard);
284
+ return auth;
285
+ }
257
286
  var authProvider = {
258
287
  name: "core.auth",
259
- register({ container, config }) {
260
- config.set("auth.allowDevHeaders", authConfig.allowDevHeaders);
261
- const apiGuard = new DatabaseTokenGuard(container);
262
- const sessionGuard = new SessionGuard(container);
263
- const jwtGuard = new JwtGuard(container);
264
- const basicGuard = new BasicAuthGuard(container);
265
- const guards = [apiGuard, jwtGuard, basicGuard, sessionGuard];
266
- if (authConfig.allowDevHeaders) {
267
- guards.push(new GuestGuard);
268
- }
269
- const auth = new AuthManager(new CompositeGuard(guards));
270
- auth.registerGuard("api", apiGuard);
271
- auth.registerGuard("access_token", apiGuard);
272
- auth.registerGuard("jwt", jwtGuard);
273
- auth.registerGuard("basic", basicGuard);
274
- auth.registerGuard("web", sessionGuard);
275
- auth.registerGuard("session", sessionGuard);
276
- container.set(CORE_AUTH_TOKEN, auth);
288
+ register({ container }) {
289
+ container.set(CORE_AUTH_TOKEN, establishedAuthReader2);
277
290
  }
278
291
  };
279
292
  var auth_default = authProvider;
280
293
 
281
- // ../../src/bootstrap/providers/cache.ts
282
- import { createCacheStore } from "@getstrata/core/cache/createCacheStore";
294
+ // ../../src/bootstrap/providers/cacheProvider.ts
295
+ import {
296
+ createCacheStore,
297
+ snapshotCacheStoreOptions
298
+ } from "@getstrata/core/cache/createCacheStore";
283
299
  import { CacheRepository } from "@getstrata/core/cache/repository";
284
- var cacheProvider = {
285
- name: "core.cache",
286
- register({ container, config, dependencies, onCleanup }) {
287
- container.singleton(CORE_CACHE_TOKEN, () => {
288
- const store = createCacheStore({
289
- driver: config.require(CACHE_DRIVER_CONFIG_KEY),
290
- ttlMs: config.require(CACHE_TTL_MS_CONFIG_KEY),
291
- maxEntries: config.require(CACHE_MAX_ENTRIES_CONFIG_KEY),
292
- redisUrl: config.get(REDIS_URL_CONFIG_KEY) || undefined
300
+ function createCacheProvider(env) {
301
+ const options = snapshotCacheStoreOptions({
302
+ driver: env.CACHE_DRIVER ?? "array",
303
+ ttlMs: Number(env.CACHE_TTL_MS ?? "3600000"),
304
+ maxEntries: Number(env.CACHE_MAX_ENTRIES ?? "100"),
305
+ redisUrl: env.REDIS_URL || undefined,
306
+ namespace: `${env.APP_KEY_PREFIX?.trim() || "strata"}:cache:v3:`
307
+ });
308
+ return Object.freeze({
309
+ name: "core.cache",
310
+ register({
311
+ container,
312
+ dependencies,
313
+ onCleanup
314
+ }) {
315
+ container.singleton(CORE_CACHE_TOKEN, () => {
316
+ const cache = new CacheRepository(createCacheStore(options));
317
+ onCleanup(() => cache.close());
318
+ return cache;
293
319
  });
294
- const cache = new CacheRepository(store);
295
- onCleanup(() => cache.close());
296
- return cache;
297
- });
298
- dependencies.cache = container.resolve(CORE_CACHE_TOKEN);
299
- }
300
- };
301
- var cache_default = cacheProvider;
320
+ dependencies.cache = container.resolve(CORE_CACHE_TOKEN);
321
+ }
322
+ });
323
+ }
302
324
 
303
325
  // ../../src/bootstrap/providers/config.ts
304
326
  import { validateEnv } from "@getstrata/core/config/envSchema";
305
-
306
- // ../../src/config/app.ts
307
- var appConfig = {
308
- name: process.env.APP_NAME?.trim() || "Strata",
309
- env: process.env.APP_ENV ?? "local",
310
- debug: (process.env.APP_DEBUG ?? "false") === "true",
311
- url: process.env.APP_URL ?? "http://localhost:3000",
312
- apiPrefix: process.env.API_PREFIX ?? "/api/v1"
313
- };
327
+ import { CORE_JSON_RESPONSE_POLICY_TOKEN } from "@getstrata/core/contracts/serviceTokens";
328
+ import { resolveMaxBodyBytes } from "@getstrata/core/http/bodySizeLimitMiddleware";
329
+ import { resolveCorsConfig } from "@getstrata/core/http/corsMiddleware";
330
+ import { resolveMaxUploadBytes } from "@getstrata/core/http/uploads";
331
+ import { envFlagEnabled, isProductionEnv } from "@getstrata/core/runtime/appEnv";
332
+ import { parseFrontendMode } from "@getstrata/core/runtime/frontendMode";
333
+ import { resolveDefaultTokenExpiryDays } from "@getstrata/core/security/tokenExpiry";
314
334
 
315
335
  // ../../src/core/queue/queueConfig.ts
316
- function resolveQueueConfig() {
317
- const driver = process.env.QUEUE_DRIVER;
318
- const maxAttempts = Number(process.env.QUEUE_MAX_ATTEMPTS ?? "3");
319
- const backoffMs = Number(process.env.QUEUE_BACKOFF_MS ?? "1000");
320
- return {
321
- driver: driver === "redis" || driver === "async" || driver === "sync" ? driver : "sync",
322
- maxAttempts: Number.isFinite(maxAttempts) && maxAttempts > 0 ? maxAttempts : 3,
323
- backoffMs: Number.isFinite(backoffMs) && backoffMs >= 0 ? backoffMs : 1000
324
- };
336
+ function snapshotQueueRetryPolicy(policy) {
337
+ const { maxAttempts, backoffMs } = policy;
338
+ if (!Number.isSafeInteger(maxAttempts) || maxAttempts < 1)
339
+ throw new TypeError("QUEUE_MAX_ATTEMPTS must be a positive safe integer.");
340
+ if (!Number.isSafeInteger(backoffMs) || backoffMs < 0 || backoffMs > 2147483647)
341
+ throw new TypeError("QUEUE_BACKOFF_MS must be a non-negative integer within the timer range.");
342
+ return Object.freeze({ maxAttempts, backoffMs });
343
+ }
344
+ function resolveQueueConfig(env = process.env) {
345
+ const driver = env.QUEUE_DRIVER ?? "sync";
346
+ if (!["sync", "async", "redis"].includes(driver))
347
+ throw new TypeError("Unknown queue driver.");
348
+ const policy = snapshotQueueRetryPolicy({
349
+ maxAttempts: Number(env.QUEUE_MAX_ATTEMPTS ?? "3"),
350
+ backoffMs: Number(env.QUEUE_BACKOFF_MS ?? "1000")
351
+ });
352
+ return Object.freeze({ driver, ...policy });
325
353
  }
326
- var queueConfig = {
327
- get driver() {
328
- return resolveQueueConfig().driver;
329
- },
330
- get maxAttempts() {
331
- return resolveQueueConfig().maxAttempts;
332
- },
333
- get backoffMs() {
334
- return resolveQueueConfig().backoffMs;
335
- }
336
- };
337
354
  // ../../src/bootstrap/env.ts
338
355
  import { defineEnvSchema } from "@getstrata/core/config/envSchema";
339
356
  import { DEFAULT_SPA_PREFIX, FRONTEND_MODE_PATTERN } from "@getstrata/core/runtime/frontendMode";
340
357
  var appEnvSchema = defineEnvSchema({
341
358
  DATABASE_URL: {
342
359
  required: true,
343
- pattern: /^(postgres(ql)?|mysql|sqlite):\/\//i
360
+ pattern: /^(?:(?:postgres(?:ql)?|mysql):\/\/\S+|sqlite:(?:\/\/)?\S+)$/i
344
361
  },
345
362
  PORT: {
346
363
  integer: true,
@@ -447,226 +464,115 @@ var appEnvSchema = defineEnvSchema({
447
464
  }
448
465
  });
449
466
 
450
- // ../../src/bootstrap/providers/config.ts
451
- function parseInteger(value, envName, minimum) {
452
- const parsed = Number.parseInt(value, 10);
453
- if (!Number.isInteger(parsed) || parsed < minimum) {
454
- const comparison = minimum === 0 ? "a non-negative" : `an integer >= ${minimum}`;
455
- throw new Error(`${envName} must be ${comparison} value.`);
456
- }
457
- return parsed;
458
- }
459
- var configProvider = {
460
- name: "core.config",
461
- register({ container, config }) {
462
- const env = validateEnv(appEnvSchema);
463
- container.set(CORE_CONFIG_TOKEN, config);
464
- if (process.env.CSRF_TARGET_ORIGIN !== undefined)
465
- config.set(CSRF_TARGET_ORIGIN_CONFIG_KEY, process.env.CSRF_TARGET_ORIGIN);
466
- config.set(DATABASE_URL_CONFIG_KEY, env.DATABASE_URL);
467
- config.set(APP_PORT_CONFIG_KEY, parseInteger(env.PORT ?? String(DEFAULT_APP_PORT), "PORT", 1));
468
- config.set(CACHE_TTL_MS_CONFIG_KEY, parseInteger(env.CACHE_TTL_MS ?? String(DEFAULT_CACHE_TTL_MS), "CACHE_TTL_MS", 0));
469
- config.set(CACHE_MAX_ENTRIES_CONFIG_KEY, parseInteger(env.CACHE_MAX_ENTRIES ?? String(DEFAULT_CACHE_MAX_ENTRIES), "CACHE_MAX_ENTRIES", 1));
470
- config.set(CACHE_DRIVER_CONFIG_KEY, env.CACHE_DRIVER ?? DEFAULT_CACHE_DRIVER);
471
- config.set(REDIS_URL_CONFIG_KEY, env.REDIS_URL ?? "");
472
- config.set("app.env", appConfig.env);
473
- config.set("app.debug", appConfig.debug);
474
- config.set("app.url", appConfig.url);
475
- config.set("app.apiPrefix", appConfig.apiPrefix);
476
- config.set("auth.allowDevHeaders", authConfig.allowDevHeaders);
477
- config.set("queue.driver", queueConfig.driver);
478
- config.set("queue.maxAttempts", queueConfig.maxAttempts);
479
- config.set("queue.backoffMs", queueConfig.backoffMs);
480
- }
467
+ // ../../src/bootstrap/rateLimit.ts
468
+ var LOCAL_LOGIN_RATE_LIMIT = {
469
+ maxAttempts: 100,
470
+ decaySeconds: 60
481
471
  };
482
- var config_default = configProvider;
483
-
484
- // ../../src/bootstrap/providers/events.ts
485
- import { eventBus } from "@getstrata/core/events";
486
- var eventsProvider = {
487
- name: "core.events",
488
- register({ container }) {
489
- container.set(CORE_EVENT_BUS_TOKEN, eventBus);
490
- }
472
+ var PRODUCTION_LOGIN_RATE_LIMIT = {
473
+ maxAttempts: 5,
474
+ decaySeconds: 900
491
475
  };
492
- var events_default = eventsProvider;
493
-
494
- // ../../src/bootstrap/discoverListeners.ts
495
- import { join as join3, resolve as resolve2 } from "path";
496
- var KEY2 = Symbol.for("@getstrata/discoverListenersState");
497
- function state2() {
498
- const globals = globalThis;
499
- globals[KEY2] ??= { loads: new Map };
500
- return globals[KEY2];
476
+ function parsePositiveInt(value, fallback) {
477
+ const parsed = Number(value);
478
+ if (!Number.isFinite(parsed) || parsed <= 0) {
479
+ return fallback;
480
+ }
481
+ return Math.trunc(parsed);
501
482
  }
502
- async function load2(options) {
503
- const listeners = new Set;
504
- const add = (value, location) => {
505
- if (typeof value !== "function")
506
- throw new TypeError(`Invalid listener registrar at ${location}: expected a default function.`);
507
- listeners.add(value);
508
- };
509
- if (options.manifest)
510
- for (const [index, value] of options.manifest.entries())
511
- add(value, `listener manifest[${index}]`);
512
- else
513
- for (const file of await infrastructureFiles(options.directory ?? join3(process.cwd(), "src", "listeners"), options.exclude)) {
514
- const exports = await importInfrastructure(file);
515
- const value = exports.default;
516
- add(value && typeof value === "object" && "default" in value ? value.default : value, file);
483
+ function parseWindowSeconds(secondsValue, msValue, fallback) {
484
+ if (secondsValue !== undefined && secondsValue.trim() !== "") {
485
+ return parsePositiveInt(secondsValue, fallback);
486
+ }
487
+ if (msValue !== undefined && msValue.trim() !== "") {
488
+ const parsedMs = Number(msValue);
489
+ if (Number.isFinite(parsedMs) && parsedMs > 0) {
490
+ return Math.max(1, Math.trunc(parsedMs / 1000));
517
491
  }
518
- return [...listeners];
519
- }
520
- function discoverListeners(options = {}) {
521
- const cache = state2().loads;
522
- const key = options.manifest ?? JSON.stringify([
523
- resolve2(options.directory ?? join3(process.cwd(), "src", "listeners")),
524
- [...options.exclude ?? []].sort()
525
- ]);
526
- const existing = cache.get(key);
527
- if (existing)
528
- return existing;
529
- const pending = load2(options).catch((error) => {
530
- if (cache.get(key) === pending)
531
- cache.delete(key);
532
- throw error;
533
- });
534
- cache.set(key, pending);
535
- return pending;
536
- }
537
- function resetDiscoverListenersForTests() {
538
- state2().loads = new Map;
539
- }
540
-
541
- // ../../src/bootstrap/listeners/invalidateCacheOnModelWrite.ts
542
- import { eventBus as eventBus2, modelEventName } from "@getstrata/core/events";
543
- import { InvalidateCacheTagsJob } from "@getstrata/core/jobs/invalidateCacheTagsJob";
544
- import { createTrackedJob } from "@getstrata/core/queue/createAppQueue";
545
-
546
- // ../../src/bootstrap/cache/modelCacheTags.ts
547
- function cacheTagsForModelWrite(tableName, action) {
548
- const module = discoverModules().find((entry) => entry.tableName === tableName);
549
- const baseTags = module?.cacheTags ?? [`${tableName}s`];
550
- const isDelete = action === "deleted" || action === "force-deleted";
551
- const extraTags = isDelete ? module?.cacheDeleteExtraTags ?? [] : [];
552
- return [...new Set([...baseTags, ...extraTags])];
553
- }
554
- function discoverModelTableNames() {
555
- return discoverModules().map((module) => module.tableName).filter((tableName) => tableName !== undefined);
556
- }
557
-
558
- // ../../src/bootstrap/listeners/invalidateCacheOnModelWrite.ts
559
- var MODEL_WRITE_ACTIONS = ["created", "updated", "deleted", "restored", "force-deleted"];
560
- var CACHE_EVENT = "strata.cache.invalidate-tags";
561
- var STATE_KEY = Symbol.for("@getstrata/modelCacheInvalidationRegistrations");
562
- function registrations() {
563
- const global = globalThis;
564
- global[STATE_KEY] ??= new WeakMap;
565
- return global[STATE_KEY];
566
- }
567
- function requireCacheTags(value) {
568
- if (!Array.isArray(value) || !value.length || value.length > 128 || !value.every((tag) => typeof tag === "string" && tag.length > 0 && tag.length <= 256))
569
- throw new Error("Invalid durable cache invalidation payload.");
570
- return value;
492
+ }
493
+ return fallback;
571
494
  }
572
- function createModelCacheInvalidationListener(resolveCache = resolveApplicationCache) {
495
+ function resolveLoginRateLimit(env = {}) {
496
+ const defaults = env.APP_ENV === "local" ? LOCAL_LOGIN_RATE_LIMIT : PRODUCTION_LOGIN_RATE_LIMIT;
573
497
  return {
574
- name: "strata.cache.invalidate-tags.v1",
575
- event: CACHE_EVENT,
576
- async handle(event, { signal }) {
577
- const payload = event.payload;
578
- if (event.version !== 1)
579
- throw new Error("Invalid durable cache invalidation version.");
580
- const tags = requireCacheTags(payload?.tags);
581
- signal.throwIfAborted();
582
- await new InvalidateCacheTagsJob(resolveCache()).handle({ tags });
583
- signal.throwIfAborted();
584
- }
498
+ maxAttempts: parsePositiveInt(env.LOGIN_RATE_LIMIT_PER_WINDOW, defaults.maxAttempts),
499
+ decaySeconds: parseWindowSeconds(env.LOGIN_RATE_LIMIT_WINDOW_SECONDS, env.LOGIN_RATE_LIMIT_WINDOW_MS, defaults.decaySeconds)
585
500
  };
586
501
  }
587
- function registerInvalidateCacheOnModelWriteListeners(bus = eventBus2, options = {}) {
588
- if (options.outbox && !options.outbox.hasListener("strata.cache.invalidate-tags.v1", CACHE_EVENT))
589
- throw new Error("The application outbox must include createModelCacheInvalidationListener().");
590
- const writes = discoverModelTableNames().flatMap((tableName) => MODEL_WRITE_ACTIONS.map((action) => ({
591
- tableName,
592
- action,
593
- tags: cacheTagsForModelWrite(tableName, action)
594
- })));
595
- if (options.outbox) {
596
- for (const write of writes)
597
- if (write.tags.length)
598
- requireCacheTags(write.tags);
599
- }
600
- const state = registrations();
601
- const previous = state.get(bus);
602
- if (previous?.durable && !options.outbox)
603
- return () => {};
604
- previous?.suspend();
605
- const unsubscribe = [];
606
- const subscribe = [];
607
- const registration = {
608
- durable: !!options.outbox,
609
- suspend() {
610
- for (const stop of unsubscribe.splice(0))
611
- stop();
612
- },
613
- resume() {
614
- for (const start of subscribe)
615
- unsubscribe.push(start());
616
- state.set(bus, registration);
617
- },
618
- dispose() {
619
- if (state.get(bus) !== registration)
620
- return;
621
- registration.suspend();
622
- if (previous)
623
- previous.resume();
624
- else
625
- state.delete(bus);
626
- }
502
+ function resolveRegisterRateLimit(env = {}) {
503
+ const defaults = env.APP_ENV === "local" ? { maxAttempts: 100, decaySeconds: 60 } : { maxAttempts: 10, decaySeconds: 60 };
504
+ return {
505
+ maxAttempts: parsePositiveInt(env.REGISTER_RATE_LIMIT_PER_WINDOW, defaults.maxAttempts),
506
+ decaySeconds: parseWindowSeconds(env.REGISTER_RATE_LIMIT_WINDOW_SECONDS, env.REGISTER_RATE_LIMIT_WINDOW_MS, defaults.decaySeconds)
627
507
  };
628
- for (const { tableName, action, tags: durableTags } of writes) {
629
- const event = modelEventName(tableName, action);
630
- if (options.outbox) {
631
- if (!durableTags.length)
632
- continue;
633
- const outbox = options.outbox;
634
- subscribe.push(() => bus.listenTransactional(event, async () => {
635
- await outbox.publish(CACHE_EVENT, { tags: durableTags });
636
- }));
637
- } else {
638
- subscribe.push(() => bus.listen(event, async () => {
639
- const tags = cacheTagsForModelWrite(tableName, action);
640
- if (!tags.length)
641
- return;
642
- let cache;
643
- let queue;
644
- try {
645
- cache = resolveApplicationCache();
646
- queue = resolveApplicationQueue();
647
- } catch {
648
- return;
649
- }
650
- const job = createTrackedJob("cache.invalidate-tags", new InvalidateCacheTagsJob(cache));
651
- await queue.dispatch(job, { tags });
652
- }));
653
- }
654
- }
655
- registration.resume();
656
- return registration.dispose;
657
508
  }
658
509
 
659
- // ../../src/bootstrap/providers/listeners.ts
660
- var listenersProvider = {
661
- name: "core.listeners",
662
- async boot({ onCleanup }) {
663
- onCleanup(registerInvalidateCacheOnModelWriteListeners());
664
- for (const registerListener of await discoverListeners()) {
665
- await registerListener();
510
+ // ../../src/bootstrap/providers/config.ts
511
+ function resolveHttpResponsePolicy(source) {
512
+ const cors = Object.freeze({
513
+ allowedOrigins: Object.freeze((source.CORS_ALLOWED_ORIGINS ?? (source.APP_URL?.trim() || "http://localhost:3000").replace(/\/$/, "")).split(",").map((origin) => origin.trim()).filter(Boolean)),
514
+ additionalAllowedHeaders: Object.freeze(source.CORS_ADDITIONAL_ALLOWED_HEADERS?.trim() ? source.CORS_ADDITIONAL_ALLOWED_HEADERS.split(",").map((name) => name.trim()) : [])
515
+ });
516
+ resolveCorsConfig(cors);
517
+ const maxAttempts = Number(source.RATE_LIMIT_PER_MINUTE ?? "120");
518
+ return Object.freeze({
519
+ cors,
520
+ securityHeaders: Object.freeze({
521
+ frontendMode: parseFrontendMode(source.FRONTEND_MODE),
522
+ production: isProductionEnv(source)
523
+ }),
524
+ maxBodyBytes: resolveMaxBodyBytes(source.MAX_REQUEST_BODY_BYTES),
525
+ rateLimitPerMinute: Number.isFinite(maxAttempts) ? maxAttempts : 120,
526
+ namespace: source.APP_KEY_PREFIX?.trim() || "strata",
527
+ trustForwardedFor: source.TRUST_FORWARDED_FOR === "true",
528
+ loginRateLimit: Object.freeze(resolveLoginRateLimit({ APP_ENV: "local", ...source })),
529
+ registerRateLimit: Object.freeze(resolveRegisterRateLimit({ APP_ENV: "local", ...source }))
530
+ });
531
+ }
532
+ function createConfigProvider(input) {
533
+ const source = Object.freeze({ ...input });
534
+ const env = validateEnv(appEnvSchema, source);
535
+ const queue = resolveQueueConfig(env);
536
+ const values = Object.freeze({
537
+ [DATABASE_URL_CONFIG_KEY]: env.DATABASE_URL,
538
+ [APP_PORT_CONFIG_KEY]: Number(env.PORT),
539
+ [CACHE_TTL_MS_CONFIG_KEY]: Number(env.CACHE_TTL_MS),
540
+ [CACHE_MAX_ENTRIES_CONFIG_KEY]: Number(env.CACHE_MAX_ENTRIES),
541
+ [CACHE_DRIVER_CONFIG_KEY]: env.CACHE_DRIVER,
542
+ [REDIS_URL_CONFIG_KEY]: env.REDIS_URL,
543
+ "http.responsePolicy": resolveHttpResponsePolicy({ ...source, APP_URL: env.APP_URL }),
544
+ "http.features": Object.freeze({
545
+ emailVerificationRequired: source.FEATURE_EMAIL_VERIFICATION === "true",
546
+ viewsEnabled: ["server-htmx", "hybrid"].includes(source.FRONTEND_MODE ?? "api"),
547
+ publicReadsEnabled: source.FEATURE_PUBLIC_READS === "true",
548
+ etagEnabled: source.FEATURE_ETAG !== "false"
549
+ }),
550
+ "http.uploadPolicy": Object.freeze({
551
+ maxBytes: resolveMaxUploadBytes(source.MAX_UPLOAD_BYTES?.trim() ?? source.MAX_REQUEST_BODY_BYTES?.trim()),
552
+ allowUnknownMime: envFlagEnabled(source.UPLOAD_ALLOW_UNKNOWN_MIME)
553
+ }),
554
+ "auth.defaultTokenExpiryDays": resolveDefaultTokenExpiryDays(source.API_TOKEN_DEFAULT_EXPIRY_DAYS),
555
+ "app.name": source.APP_NAME?.trim() || "Strata",
556
+ "app.env": env.APP_ENV,
557
+ "app.debug": source.APP_DEBUG === "true",
558
+ "app.url": env.APP_URL,
559
+ "app.apiPrefix": env.API_PREFIX,
560
+ "auth.allowDevHeaders": envFlagEnabled(env.AUTH_DEV_HEADERS),
561
+ "queue.driver": queue.driver,
562
+ "queue.maxAttempts": queue.maxAttempts,
563
+ "queue.backoffMs": queue.backoffMs,
564
+ ...source.CSRF_TARGET_ORIGIN !== undefined ? { [CSRF_TARGET_ORIGIN_CONFIG_KEY]: source.CSRF_TARGET_ORIGIN } : {}
565
+ });
566
+ return Object.freeze({
567
+ name: "core.config",
568
+ register({ container, config }) {
569
+ container.set(CORE_CONFIG_TOKEN, config);
570
+ container.set(CORE_JSON_RESPONSE_POLICY_TOKEN, Object.freeze({ etagEnabled: source.FEATURE_ETAG !== "false" }));
571
+ for (const [key, value] of Object.entries(values))
572
+ config.set(key, value);
666
573
  }
667
- }
668
- };
669
- var listeners_default = listenersProvider;
574
+ });
575
+ }
670
576
 
671
577
  // ../../src/bootstrap/providers/policy.ts
672
578
  import { PolicyGate } from "@getstrata/core/auth/policy";
@@ -679,27 +585,83 @@ var policyProvider = {
679
585
  var policy_default = policyProvider;
680
586
 
681
587
  // ../../src/bootstrap/providers/queue.ts
588
+ import { createAuditExporter } from "@getstrata/core/audit/exportAuditLogs";
682
589
  import {
683
590
  createAppQueue,
684
- createFailedJobService,
591
+ createSystemQueueServices,
685
592
  FAILED_JOB_SERVICE_TOKEN
686
593
  } from "@getstrata/core/queue/createAppQueue";
594
+ import { JobRegistry, QUEUE_JOB_REGISTRY_TOKEN } from "@getstrata/core/queue/jobRegistry";
595
+ import { resolveQueueConfig as resolveQueueConfig2, resolveQueueRuntimeConfig } from "@getstrata/core/queue/queueConfig";
687
596
 
688
597
  // ../../src/bootstrap/discoverJobs.ts
689
- import { join as join4, resolve as resolve3 } from "path";
598
+ import { join as join2, resolve } from "path";
690
599
  import { Job } from "@getstrata/core/queue";
691
- import { jobRegistry } from "@getstrata/core/queue/jobRegistry";
692
- var KEY3 = Symbol.for("@getstrata/discoverJobsState");
693
- function state3() {
694
- const globals = globalThis;
695
- globals[KEY3] ??= { loads: new Map, registered: new Map };
696
- return globals[KEY3];
600
+
601
+ // ../../src/bootstrap/infrastructureDiscovery.ts
602
+ import { readdir } from "fs/promises";
603
+ import { join, relative } from "path";
604
+ import { pathToFileURL } from "url";
605
+ async function infrastructureFiles(directory, exclude = []) {
606
+ const excluded = new Set([
607
+ "index.ts",
608
+ "index.js",
609
+ "index.mts",
610
+ "index.mjs",
611
+ "register.ts",
612
+ "register.js",
613
+ "register.mts",
614
+ "register.mjs",
615
+ ...exclude
616
+ ]);
617
+ const files = [];
618
+ async function visit(path) {
619
+ const entries = await readdir(path, { withFileTypes: true });
620
+ entries.sort((a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0);
621
+ for (const entry of entries) {
622
+ const file = join(path, entry.name);
623
+ const key = relative(directory, file).replaceAll("\\", "/");
624
+ if (excluded.has(entry.name) || excluded.has(key))
625
+ continue;
626
+ if (entry.isDirectory())
627
+ await visit(file);
628
+ else if (entry.isFile() && /\.(ts|js|mts|mjs)$/.test(entry.name) && !/\.(d|test|spec)\.[cm]?[jt]s$/.test(entry.name))
629
+ files.push(file);
630
+ }
631
+ }
632
+ try {
633
+ await visit(directory);
634
+ } catch (error) {
635
+ if (error.code !== "ENOENT")
636
+ throw error;
637
+ if (error.path !== directory)
638
+ throw error;
639
+ }
640
+ return files;
641
+ }
642
+ async function importInfrastructure(file) {
643
+ try {
644
+ return await import(pathToFileURL(file).href);
645
+ } catch (error) {
646
+ throw new Error(`Cannot load infrastructure module ${file}`, { cause: error });
647
+ }
648
+ }
649
+
650
+ // ../../src/bootstrap/discoverJobs.ts
651
+ var states = new WeakMap;
652
+ function state(registry) {
653
+ let value = states.get(registry);
654
+ if (!value) {
655
+ value = { loads: new Map, registered: new Map };
656
+ states.set(registry, value);
657
+ }
658
+ return value;
697
659
  }
698
660
  function validateClass(value, location) {
699
661
  if (typeof value !== "function" || typeof value.jobName !== "string" || !value.jobName.trim() || !(value.prototype instanceof Job) && typeof value.prototype?.handle !== "function")
700
662
  throw new TypeError(`Invalid job at ${location}: expected a class with nonempty static jobName and handle().`);
701
663
  }
702
- async function load3(options, current) {
664
+ async function load(registry, options, current) {
703
665
  const jobs = new Map;
704
666
  const add = (name, identity, create, location) => {
705
667
  const previous = jobs.get(name);
@@ -721,7 +683,7 @@ async function load3(options, current) {
721
683
  }
722
684
  }
723
685
  } else {
724
- for (const file of await infrastructureFiles(options.directory ?? join4(process.cwd(), "src", "jobs"), options.exclude)) {
686
+ for (const file of await infrastructureFiles(options.directory ?? join2(process.cwd(), "src", "jobs"), options.exclude)) {
725
687
  const exports = await importInfrastructure(file);
726
688
  const defaultValue = exports.default;
727
689
  const legacy = defaultValue && typeof defaultValue === "object" && "default" in defaultValue ? defaultValue.default : defaultValue;
@@ -744,31 +706,31 @@ async function load3(options, current) {
744
706
  }
745
707
  if (!current())
746
708
  return [...jobs.keys()];
747
- const registered = state3().registered;
709
+ const registered = state(registry).registered;
748
710
  for (const [name, entry] of jobs) {
749
711
  const previous = registered.get(name);
750
712
  if (previous && previous.identity !== entry.identity)
751
713
  throw new Error(`Duplicate discovered job "${name}" at ${entry.location}; first declared at ${previous.location}.`);
752
714
  }
753
- const existing = new Set(jobRegistry.names());
715
+ const existing = new Set(registry.names());
754
716
  for (const [name, entry] of jobs) {
755
717
  if (!existing.has(name)) {
756
- jobRegistry.register(name, entry.create);
718
+ registry.register(name, entry.create);
757
719
  registered.set(name, entry);
758
720
  }
759
721
  }
760
722
  return [...jobs.keys()];
761
723
  }
762
- function discoverJobs(options = {}) {
763
- const cache = state3().loads;
724
+ function discoverJobs(registry, options = {}) {
725
+ const cache = state(registry).loads;
764
726
  const key = options.manifest ?? JSON.stringify([
765
- resolve3(options.directory ?? join4(process.cwd(), "src", "jobs")),
727
+ resolve(options.directory ?? join2(process.cwd(), "src", "jobs")),
766
728
  [...options.exclude ?? []].sort()
767
729
  ]);
768
730
  const existing = cache.get(key);
769
731
  if (existing)
770
732
  return existing;
771
- const pending = load3(options, () => state3().loads === cache).catch((error) => {
733
+ const pending = load(registry, options, () => state(registry).loads === cache).catch((error) => {
772
734
  if (cache.get(key) === pending)
773
735
  cache.delete(key);
774
736
  throw error;
@@ -776,286 +738,289 @@ function discoverJobs(options = {}) {
776
738
  cache.set(key, pending);
777
739
  return pending;
778
740
  }
779
- function resetDiscoverJobsForTests() {
780
- state3().loads = new Map;
781
- state3().registered = new Map;
741
+ function resetDiscoverJobsForTests(registry) {
742
+ state(registry).loads = new Map;
743
+ state(registry).registered = new Map;
782
744
  }
783
745
 
784
746
  // ../../src/bootstrap/queue/defaultJobs.ts
785
747
  import { ExportAuditLogsJob } from "@getstrata/core/jobs/exportAuditLogsJob";
786
- import { InvalidateCacheTagsJob as InvalidateCacheTagsJob2 } from "@getstrata/core/jobs/invalidateCacheTagsJob";
787
- import { jobRegistry as jobRegistry2 } from "@getstrata/core/queue/jobRegistry";
788
- import { resolveApplicationCache as resolveApplicationCache2 } from "@getstrata/core/runtime/applicationRegistry";
789
- function registerDefaultJobs() {
790
- jobRegistry2.register("cache.invalidate-tags", () => {
791
- return new InvalidateCacheTagsJob2(resolveApplicationCache2());
748
+ import { InvalidateCacheTagsJob } from "@getstrata/core/jobs/invalidateCacheTagsJob";
749
+ var SYSTEM_JOB_NAMES = Object.freeze([
750
+ InvalidateCacheTagsJob.jobName,
751
+ ExportAuditLogsJob.jobName
752
+ ]);
753
+ function registerDefaultJobs(registry) {
754
+ registry.register(InvalidateCacheTagsJob.jobName, () => {
755
+ return new InvalidateCacheTagsJob;
792
756
  });
793
- jobRegistry2.register("audit.export", () => new ExportAuditLogsJob);
757
+ registry.register(ExportAuditLogsJob.jobName, () => new ExportAuditLogsJob);
794
758
  }
795
759
 
796
760
  // ../../src/bootstrap/providers/queue.ts
797
- var queueProvider = {
798
- name: "core.queue",
799
- async register({ container, config, onCleanup }) {
800
- const configuredDriver = process.env.QUEUE_DRIVER ?? DEFAULT_QUEUE_DRIVER;
801
- const driver = configuredDriver === "async" || configuredDriver === "redis" || configuredDriver === "sync" ? configuredDriver : DEFAULT_QUEUE_DRIVER;
802
- config.set("queue.driver", driver);
803
- const failedJobs = createFailedJobService();
804
- container.set(FAILED_JOB_SERVICE_TOKEN, failedJobs);
805
- registerDefaultJobs();
806
- await discoverJobs();
807
- const queue = createAppQueue(driver, config.get(REDIS_URL_CONFIG_KEY) ?? process.env.REDIS_URL, failedJobs);
808
- onCleanup(() => queue.close?.(), driver === "async" ? "drain" : "close");
809
- container.set(CORE_QUEUE_TOKEN, queue);
810
- }
811
- };
812
- var queue_default = queueProvider;
761
+ function createQueueProvider(env = process.env, handoff) {
762
+ const environment = Object.freeze({ ...env });
763
+ const retryPolicy = resolveQueueConfig2(environment);
764
+ const runtime = resolveQueueRuntimeConfig(environment);
765
+ return {
766
+ name: "core.queue",
767
+ async register({ container, config, onCleanup, invoke }) {
768
+ const configuredDriver = environment.QUEUE_DRIVER ?? DEFAULT_QUEUE_DRIVER;
769
+ const driver = configuredDriver === "async" || configuredDriver === "redis" || configuredDriver === "sync" ? configuredDriver : DEFAULT_QUEUE_DRIVER;
770
+ config.set("queue.driver", driver);
771
+ const failedJobs = createSystemQueueServices(invoke, {
772
+ cache: container.resolve(CORE_CACHE_TOKEN),
773
+ auditExport: createAuditExporter({
774
+ environment,
775
+ 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))
776
+ })
777
+ }, handoff, SYSTEM_JOB_NAMES);
778
+ container.set(FAILED_JOB_SERVICE_TOKEN, failedJobs);
779
+ const registry = new JobRegistry;
780
+ registerDefaultJobs(registry);
781
+ await discoverJobs(registry);
782
+ const queue = createAppQueue(driver, config.get(REDIS_URL_CONFIG_KEY) ?? environment.REDIS_URL, failedJobs, registry, retryPolicy, runtime);
783
+ onCleanup(() => queue.close?.(), driver === "async" ? "drain" : "close");
784
+ container.set(CORE_QUEUE_TOKEN, queue);
785
+ container.set(QUEUE_JOB_REGISTRY_TOKEN, registry);
786
+ }
787
+ };
788
+ }
813
789
 
814
790
  // ../../src/bootstrap/providers/storage.ts
815
- import { createStorageDriver, StorageManager } from "@getstrata/core/storage/storage";
816
- var storageProvider = {
817
- name: "core.storage",
818
- register({ dependencies }) {
819
- dependencies.storage = new StorageManager(createStorageDriver());
820
- }
821
- };
822
- var storage_default = storageProvider;
791
+ import { service } from "@getstrata/core/contracts/services";
792
+ import {
793
+ CORE_STORAGE_TOKEN,
794
+ createStorageDriver,
795
+ StorageManager,
796
+ snapshotStorageConfig
797
+ } from "@getstrata/core/storage/storage";
798
+ function assertStorageDriver(driver) {
799
+ if (!driver || [driver.put, driver.get, driver.delete].some((method) => typeof method !== "function"))
800
+ throw new TypeError("Storage requires put, get, and delete capabilities.");
801
+ }
802
+ function createStorageProvider(driver) {
803
+ assertStorageDriver(driver);
804
+ return Object.freeze({
805
+ name: "core.storage",
806
+ register({ dependencies }) {
807
+ dependencies.storage = new StorageManager(driver);
808
+ }
809
+ });
810
+ }
823
811
 
824
812
  // ../../src/bootstrap/providers/tracing.ts
825
- import { acquireTracingRuntime } from "@getstrata/core/tracing/tracingMiddleware";
826
- var tracingProvider = {
827
- name: "core.tracing",
828
- register({ onCleanup }) {
829
- const ownership = acquireTracingRuntime();
830
- onCleanup(() => ownership.flush(), "flush");
831
- onCleanup(() => ownership.release(), "close");
832
- }
833
- };
834
- var tracing_default = tracingProvider;
813
+ import { CORE_TRACING_RUNTIME_TOKEN } from "@getstrata/core/contracts/serviceTokens";
814
+ import {
815
+ captureTracingOptions,
816
+ createTracingRuntime
817
+ } from "@getstrata/core/tracing/tracingMiddleware";
818
+ function createTracingProvider(options = {}) {
819
+ const configured = captureTracingOptions(options);
820
+ let registered = false;
821
+ return {
822
+ name: "core.tracing",
823
+ register({ container, onCleanup }) {
824
+ if (registered)
825
+ throw new Error("A tracing provider belongs to one application context; create a new provider for each context.");
826
+ registered = true;
827
+ const runtime = createTracingRuntime(configured);
828
+ onCleanup(() => runtime.shutdown(), "close");
829
+ onCleanup(() => runtime.forceFlush(), "flush");
830
+ container.set(CORE_TRACING_RUNTIME_TOKEN, runtime);
831
+ }
832
+ };
833
+ }
835
834
 
836
835
  // ../../src/bootstrap/providers/view.ts
837
- import { currentRequestMeta } from "@getstrata/core/http/requestMetaContext";
838
- import { appDisplayName } from "@getstrata/core/runtime/appKeyPrefix";
839
- import { isViewsEnabled } from "@getstrata/core/runtime/frontendMode";
836
+ import { resolve as resolve2 } from "path";
837
+ import { csrfTokenOptionsFromEnvironment } from "@getstrata/core/http/csrfToken";
838
+ import { flashSessionOptionsFromEnvironment } from "@getstrata/core/http/flashSession";
839
+ import { isViewsMode, parseFrontendMode as parseFrontendMode2 } from "@getstrata/core/runtime/frontendMode";
840
840
  import {
841
- CORE_VIEW_RENDERER_TOKEN,
842
- configureWebErrorView,
843
- configureWebLayoutData,
841
+ createWebErrorView,
844
842
  createWebLayoutDataResolver,
845
- DEFAULT_VIEWS_DIRECTORY,
846
843
  EtaViewEngine,
847
844
  errorTemplateName,
848
- resolveWebLayoutData,
849
845
  ViewRenderer
850
846
  } from "@getstrata/core/view";
851
- var CORE_VIEW_TOKEN = "core.view";
847
+ import {
848
+ CORE_VIEW_RENDERER_TOKEN,
849
+ CORE_VIEW_TOKEN,
850
+ CORE_WEB_ERROR_VIEW_TOKEN
851
+ } from "@getstrata/core/view/tokens";
852
852
  var VIEW_DIRECTORY_CONFIG_KEY = "view.directory";
853
853
  function createViewProvider(options = {}) {
854
- const directory = options.directory;
854
+ const env = { ...options.env ?? process.env };
855
+ const enabled = options.enabled ?? isViewsMode(parseFrontendMode2(env.FRONTEND_MODE));
856
+ const directory = resolve2(options.rootDir ?? process.cwd(), options.directory ?? (env.VIEW_DIRECTORY?.trim() || "resources/views"));
855
857
  const layout = options.layout;
856
- const data = { ...options.data };
858
+ const appName = env.APP_NAME?.trim() || "Strata";
859
+ const extra = options.data?.extra;
860
+ const defaults = { appName, currentOrganization: null, organizations: [] };
861
+ const data = {
862
+ ...options.data,
863
+ csrf: options.data?.csrf ? { ...options.data.csrf } : enabled ? csrfTokenOptionsFromEnvironment(env) : undefined,
864
+ flash: options.data?.flash ? { ...options.data.flash } : enabled ? flashSessionOptionsFromEnvironment(env) : undefined,
865
+ extra: typeof extra === "function" ? async (user) => ({ ...defaults, ...await extra(user) }) : { ...defaults, ...extra }
866
+ };
867
+ const customErrorRender = options.error?.render;
857
868
  return {
858
869
  name: "view",
859
870
  register({ container, config }) {
860
- if (!(options.enabled ?? isViewsEnabled()))
871
+ if (!enabled)
861
872
  return;
862
- const viewsDirectory = directory ?? (process.env.VIEW_DIRECTORY?.trim() || DEFAULT_VIEWS_DIRECTORY);
863
- config.set(VIEW_DIRECTORY_CONFIG_KEY, viewsDirectory);
864
- const engine = new EtaViewEngine(viewsDirectory, createWebLayoutDataResolver(container, data));
873
+ config.set(VIEW_DIRECTORY_CONFIG_KEY, directory);
874
+ const engine = new EtaViewEngine(directory, createWebLayoutDataResolver(container, data));
865
875
  container.set(CORE_VIEW_TOKEN, engine);
866
876
  container.set(CORE_VIEW_RENDERER_TOKEN, new ViewRenderer(engine, layout));
877
+ container.set(CORE_WEB_ERROR_VIEW_TOKEN, createWebErrorView({
878
+ render: customErrorRender ?? ((input) => engine.render(errorTemplateName(input.status), {
879
+ title: input.title,
880
+ message: input.message,
881
+ errors: input.errors
882
+ }, { layout, request: input.request }))
883
+ }));
867
884
  }
868
885
  };
869
886
  }
870
- var viewProvider = {
871
- name: "view",
872
- register({ container, config }) {
873
- if (!isViewsEnabled()) {
874
- return;
875
- }
876
- const viewsDirectory = process.env.VIEW_DIRECTORY?.trim() || DEFAULT_VIEWS_DIRECTORY;
877
- config.set(VIEW_DIRECTORY_CONFIG_KEY, viewsDirectory);
878
- const engine = new EtaViewEngine(viewsDirectory, (request) => resolveWebLayoutData(container, request ?? currentRequestMeta().request));
879
- container.set(CORE_VIEW_TOKEN, engine);
880
- container.set(CORE_VIEW_RENDERER_TOKEN, new ViewRenderer(engine));
881
- configureWebLayoutData({
882
- extra: async () => ({
883
- appName: appDisplayName(),
884
- currentOrganization: null,
885
- organizations: []
886
- })
887
- });
888
- configureWebErrorView({
889
- render: async (input) => engine.render(errorTemplateName(input.status), {
890
- title: input.title,
891
- message: input.message,
892
- errors: input.errors
893
- })
894
- });
895
- }
896
- };
897
887
 
898
888
  // ../../src/bootstrap/providers/index.ts
899
- var coreProviders = [
900
- config_default,
901
- tracing_default,
902
- cache_default,
903
- storage_default,
904
- auth_default,
905
- events_default,
906
- policy_default,
907
- queue_default,
908
- listeners_default,
909
- viewProvider
910
- ];
889
+ function createCoreProviders(env = process.env) {
890
+ env = Object.freeze({ ...env });
891
+ const configProvider = createConfigProvider(env);
892
+ const cacheProvider = createCacheProvider(env);
893
+ const storageProvider = createStorageProvider(createStorageDriver2(resolveStorageConfig(env)));
894
+ return [
895
+ configProvider,
896
+ createTracingProvider({ env }),
897
+ cacheProvider,
898
+ storageProvider,
899
+ auth_default,
900
+ policy_default,
901
+ createQueueProvider(env),
902
+ createViewProvider({ env })
903
+ ];
904
+ }
911
905
 
912
906
  // ../../src/bootstrap/context.ts
913
- function collectProviders(modules = discoverModules()) {
914
- return [...coreProviders, ...modules.flatMap((module) => module.providers ?? [])];
907
+ function collectProviders(modules = []) {
908
+ return [...createCoreProviders(), ...modules.flatMap((module) => module.providers ?? [])];
915
909
  }
916
910
  async function runProviderPhase(providers, phase, context) {
917
911
  for (const provider of providers)
918
912
  await provider[phase]?.(context);
919
913
  }
920
- var readyContext;
921
- async function createAppContext(providers) {
922
- if (!providers)
923
- await ensureModulesLoaded();
924
- const configured = [...providers ?? collectProviders()];
914
+ function createApplicationContext(providers, options) {
915
+ if (!options)
916
+ throw new TypeError("Explicit application definition and connection are required.");
917
+ const configured = [...providers];
925
918
  const container = new ServiceContainer;
926
919
  const config = new ConfigStore;
927
- const dependencies = { container };
928
- const cleanups = [];
929
- const drains = [];
930
- let drainStarted = false;
931
- let draining;
932
- const drain = () => {
933
- drainStarted = true;
934
- draining ??= (async () => {
935
- const errors = [];
936
- for (const handler of drains.splice(0).reverse()) {
937
- try {
938
- await handler();
939
- } catch (error) {
940
- errors.push(error);
941
- }
942
- }
943
- if (errors.length)
944
- throw new AggregateError(errors, "Provider drain failed.");
945
- })();
946
- return draining;
920
+ if (options.http)
921
+ container.set(HTTP_PERSISTENCE_OPTIONS, Object.freeze({ ...options.http }));
922
+ const cleanups = {
923
+ drain: [],
924
+ flush: [],
925
+ close: []
947
926
  };
948
- const flushes = [];
949
- let flushStarted = false;
950
- let flushing;
951
- const flush = () => {
952
- flushStarted = true;
953
- flushing ??= (async () => {
927
+ const started = new Set;
928
+ const results = new Map;
929
+ const phase = (name) => {
930
+ const old = results.get(name);
931
+ if (old)
932
+ return old;
933
+ started.add(name);
934
+ const result = Promise.resolve().then(async () => {
954
935
  const errors = [];
955
- for (const handler of flushes.splice(0).reverse()) {
936
+ for (const callback of cleanups[name].splice(0).reverse()) {
956
937
  try {
957
- await handler();
938
+ await callback();
958
939
  } catch (error) {
959
940
  errors.push(error);
960
941
  }
961
942
  }
962
943
  if (errors.length)
963
- throw new AggregateError(errors, "Provider flush failed.");
964
- })();
965
- return flushing;
966
- };
967
- let disposal;
968
- let disposed = false;
969
- let initialized;
970
- const dispose = () => {
971
- disposed = true;
972
- disposal ??= (async () => {
973
- await drain();
974
- const errors = [];
975
- try {
976
- await flush();
977
- } catch (error) {
978
- errors.push(error);
979
- }
980
- if (initialized) {
981
- clearActiveApplicationContext(initialized);
982
- if (readyContext === initialized)
983
- readyContext = undefined;
984
- }
985
- for (const handler of cleanups.splice(0).reverse()) {
986
- try {
987
- await handler();
988
- } catch (error) {
989
- errors.push(error);
990
- }
991
- }
992
- if (errors.length)
993
- throw new AggregateError(errors, "Provider cleanup failed.");
994
- })();
995
- return disposal;
944
+ throw new AggregateError(errors, `Provider ${name} failed.`);
945
+ });
946
+ results.set(name, result);
947
+ result.catch(() => {});
948
+ return result;
996
949
  };
950
+ let application;
951
+ const invoke = (envelope, work) => createPersistenceInvocation(application, options.connection)(envelope, work);
952
+ const dependencies = { container, invoke };
997
953
  const context = {
998
954
  container,
999
955
  config,
1000
956
  dependencies,
1001
- onCleanup(handler, phase = "close") {
1002
- if (disposed)
1003
- throw new Error("Cannot register cleanup on a disposed application context.");
1004
- if (phase !== "drain" && phase !== "flush" && phase !== "close")
957
+ invoke,
958
+ onCleanup(callback, name = "close") {
959
+ if (!["drain", "flush", "close"].includes(name))
1005
960
  throw new TypeError("Unknown provider cleanup phase.");
1006
- if (phase === "drain" && drainStarted || phase === "flush" && flushStarted)
961
+ if (started.has("close"))
962
+ throw new Error("Cannot register cleanup on a disposed application context.");
963
+ if (started.has(name))
1007
964
  throw new Error("Cannot register cleanup after its phase started.");
1008
- (phase === "drain" ? drains : phase === "flush" ? flushes : cleanups).push(handler);
965
+ cleanups[name].push(callback);
1009
966
  }
1010
967
  };
1011
- container.set(CORE_HTTP_CLEANUP_TOKEN2, (handler) => context.onCleanup(handler));
1012
- try {
1013
- await runProviderPhase(configured, "register", context);
1014
- await runProviderPhase(configured, "boot", context);
1015
- assertAppDependenciesComplete(dependencies);
1016
- const appContext = {
1017
- container,
1018
- config,
1019
- dependencies,
1020
- drain,
1021
- flush,
1022
- dispose
1023
- };
1024
- initialized = appContext;
1025
- setActiveApplicationContext(appContext);
1026
- readyContext = appContext;
1027
- return appContext;
1028
- } catch (error) {
1029
- try {
1030
- await dispose();
1031
- } catch (cleanupError) {
1032
- throw new AggregateError([error, cleanupError], "Application startup and cleanup failed.", {
1033
- cause: error
968
+ container.set(CORE_HTTP_CLEANUP_TOKEN2, (callback) => context.onCleanup(callback));
969
+ application = createApplication({
970
+ ...options.definition,
971
+ providers: [
972
+ ...options.definition.providers,
973
+ {
974
+ name: "bootstrap.providers",
975
+ setup: async (scope) => {
976
+ await scope.acquire({
977
+ name: "bootstrap.providers",
978
+ open: () => ({ ok: true, value: context }),
979
+ drain: () => phase("drain"),
980
+ flush: () => phase("flush"),
981
+ close: () => phase("close")
982
+ });
983
+ const selected = [...configured, ...options.providersFromScope?.(scope) ?? []];
984
+ await runProviderPhase(selected, "register", context);
985
+ await runProviderPhase(selected, "boot", context);
986
+ assertAppDependenciesComplete(dependencies);
987
+ }
988
+ }
989
+ ]
990
+ });
991
+ options.onConstructed?.(Object.freeze({ application, invoke }));
992
+ let startup;
993
+ return Object.freeze({
994
+ application,
995
+ invoke,
996
+ start: () => startup ??= (async () => {
997
+ await application.start();
998
+ assertAppDependenciesComplete(dependencies);
999
+ return Object.freeze({
1000
+ container,
1001
+ config,
1002
+ dependencies,
1003
+ application,
1004
+ invoke,
1005
+ drain: () => phase("drain"),
1006
+ flush: () => phase("flush"),
1007
+ dispose: async () => {
1008
+ const result = await application.stop();
1009
+ if (!result.successful)
1010
+ throw new Error("Application shutdown is incomplete.");
1011
+ }
1034
1012
  });
1035
- }
1036
- throw error;
1037
- }
1013
+ })()
1014
+ });
1038
1015
  }
1039
- function getAppContext() {
1040
- if (!readyContext)
1041
- throw new Error("Application context is not ready. Await createAppContext() before using appContext.");
1042
- return readyContext;
1016
+ async function createAppContext(providers, options) {
1017
+ const selected = providers ?? collectProviders();
1018
+ return createApplicationContext(selected, options).start();
1043
1019
  }
1044
- var appContext = {
1045
- get container() {
1046
- return getAppContext().container;
1047
- },
1048
- get config() {
1049
- return getAppContext().config;
1050
- },
1051
- get dependencies() {
1052
- return getAppContext().dependencies;
1053
- }
1054
- };
1055
1020
 
1056
1021
  // ../../src/bootstrap/dependencies.ts
1057
- async function createAppDependencies() {
1058
- return (await createAppContext()).dependencies;
1022
+ async function createAppDependencies(providers, options) {
1023
+ return (await createAppContext(providers, options)).dependencies;
1059
1024
  }
1060
1025
  export {
1061
1026
  createAppContext,