@getstrata/bootstrap 2.2.59 → 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.
- package/CHANGELOG.md +28 -0
- package/dist/bootstrap/app.d.ts +18 -7
- package/dist/bootstrap/buildModuleRoutes.d.ts +3 -5
- package/dist/bootstrap/buildWebModuleRoutes.d.ts +2 -3
- package/dist/bootstrap/cache/modelCacheTags.d.ts +3 -2
- package/dist/bootstrap/cachedJson.d.ts +7 -2
- package/dist/bootstrap/config.d.ts +1 -1
- package/dist/bootstrap/context.d.ts +25 -7
- package/dist/bootstrap/contracts.d.ts +1 -0
- package/dist/bootstrap/createWebRoutes.d.ts +2 -1
- package/dist/bootstrap/databaseReadiness.d.ts +3 -0
- package/dist/bootstrap/dependencies.d.ts +3 -2
- package/dist/bootstrap/discoverJobs.d.ts +3 -2
- package/dist/bootstrap/discoverListeners.d.ts +10 -7
- package/dist/bootstrap/discoverModels.d.ts +3 -2
- package/dist/bootstrap/discoverModules.d.ts +7 -6
- package/dist/bootstrap/health.d.ts +3 -2
- package/dist/bootstrap/http/securedRouteModelBinding.d.ts +1 -1
- package/dist/bootstrap/httpKernel.d.ts +43 -22
- package/dist/bootstrap/httpPersistence.d.ts +4 -0
- package/dist/bootstrap/inProcessCron.d.ts +5 -5
- package/dist/bootstrap/listeners/invalidateCacheOnModelWrite.d.ts +13 -12
- package/dist/bootstrap/metricsRoutes.d.ts +6 -1
- package/dist/bootstrap/moduleRouteMiddleware.d.ts +4 -4
- package/dist/bootstrap/modules.d.ts +1 -1
- package/dist/bootstrap/ownedHttpRoute.d.ts +23 -0
- package/dist/bootstrap/persistenceContracts.d.ts +70 -0
- package/dist/bootstrap/persistenceInvocation.d.ts +4 -0
- package/dist/bootstrap/providers/auth.d.ts +21 -0
- package/dist/bootstrap/providers/cache.d.ts +9 -3
- package/dist/bootstrap/providers/cacheProvider.d.ts +3 -0
- package/dist/bootstrap/providers/config.d.ts +6 -3
- package/dist/bootstrap/providers/events.d.ts +5 -2
- package/dist/bootstrap/providers/index.d.ts +3 -2
- package/dist/bootstrap/providers/listeners.d.ts +3 -3
- package/dist/bootstrap/providers/mail.d.ts +15 -0
- package/dist/bootstrap/providers/queue.d.ts +3 -2
- package/dist/bootstrap/providers/storage.d.ts +11 -2
- package/dist/bootstrap/providers/tracing.d.ts +4 -2
- package/dist/bootstrap/providers/view.d.ts +8 -5
- package/dist/bootstrap/public-api.d.ts +10 -7
- package/dist/bootstrap/queue/defaultJobs.d.ts +4 -2
- package/dist/bootstrap/rateLimit.d.ts +13 -3
- package/dist/bootstrap/routeCompiler.d.ts +20 -0
- package/dist/bootstrap/routeMetadata.d.ts +3 -3
- package/dist/bootstrap/routePlan.d.ts +11 -0
- package/dist/bootstrap/schedule.d.ts +11 -2
- package/dist/bootstrap/secretsGuard.d.ts +2 -3
- package/dist/bootstrap/web/routing.d.ts +6 -3
- package/dist/bootstrap/web/server.d.ts +14 -4
- package/dist/bootstrap/web/session.d.ts +23 -16
- package/dist/entries/buildModuleRoutes.js +602 -384
- package/dist/entries/buildWebModuleRoutes.js +596 -347
- package/dist/entries/cache/modelCacheTags.js +8 -186
- package/dist/entries/cachedJson.js +22 -0
- package/dist/entries/config.js +1 -3
- package/dist/entries/context.js +665 -700
- package/dist/entries/createSpaRoutes.js +194 -5
- package/dist/entries/createWebRoutes.js +618 -367
- package/dist/entries/databaseReadiness.js +267 -0
- package/dist/entries/dependencies.js +666 -701
- package/dist/entries/discoverJobs.js +18 -16
- package/dist/entries/discoverListeners.js +27 -38
- package/dist/entries/discoverModels.js +4 -3
- package/dist/entries/discoverModules.js +29 -67
- package/dist/entries/health.js +14 -34
- package/dist/entries/httpKernel.js +405 -89
- package/dist/entries/listeners/invalidateCacheOnModelWrite.js +43 -289
- package/dist/entries/metricsRoutes.js +9 -5
- package/dist/entries/persistenceContracts.js +1 -0
- package/dist/entries/persistenceInvocation.js +17 -0
- package/dist/entries/providers/auth.js +114 -0
- package/dist/entries/providers/cache.js +35 -0
- package/dist/entries/providers/events.js +55 -0
- package/dist/entries/providers/view.js +34 -44
- package/dist/entries/providers.js +392 -561
- package/dist/entries/queue/defaultJobs.js +9 -6
- package/dist/entries/routePlan.js +200 -0
- package/dist/entries/schedule.js +37 -37
- package/dist/entries/secretsGuard.js +10 -13
- package/dist/entries/web/routing.js +412 -96
- package/dist/entries/web/server.js +461 -29
- package/dist/entries/web/session.js +61 -73
- package/dist/index.js +1520 -1085
- package/dist/internal/ownedHttpRoute.js +66 -0
- package/package.json +52 -15
- package/dist/bootstrap/applicationRegistry.d.ts +0 -1
- package/dist/bootstrap/routeRegistry.d.ts +0 -10
- package/dist/entries/applicationRegistry.js +0 -24
- package/dist/entries/routeRegistry.js +0 -29
|
@@ -1,22 +1,20 @@
|
|
|
1
1
|
// @bun
|
|
2
|
+
// ../../src/bootstrap/providers/index.ts
|
|
3
|
+
import { createStorageDriver as createStorageDriver2, resolveStorageConfig } from "@getstrata/core/storage/storage";
|
|
4
|
+
|
|
2
5
|
// ../../src/bootstrap/providers/auth.ts
|
|
6
|
+
import { establishedAuthReader } from "@getstrata/core/auth/authReader";
|
|
3
7
|
import { BasicAuthGuard } from "@getstrata/core/auth/basicAuthGuard";
|
|
4
8
|
import {
|
|
5
9
|
AuthManager,
|
|
6
10
|
CompositeGuard,
|
|
7
11
|
DatabaseTokenGuard,
|
|
8
|
-
GuestGuard
|
|
12
|
+
GuestGuard,
|
|
13
|
+
requireAuthCapability
|
|
9
14
|
} from "@getstrata/core/auth/guard";
|
|
10
15
|
import { JwtGuard } from "@getstrata/core/auth/jwtGuard";
|
|
11
16
|
import { SessionGuard } from "@getstrata/core/auth/sessionGuard";
|
|
12
17
|
|
|
13
|
-
// ../../src/config/auth.ts
|
|
14
|
-
import { envFlagEnabled } from "@getstrata/core/runtime/appEnv";
|
|
15
|
-
var authConfig = {
|
|
16
|
-
allowDevHeaders: envFlagEnabled(process.env.AUTH_DEV_HEADERS),
|
|
17
|
-
tokenDefaultAbilities: []
|
|
18
|
-
};
|
|
19
|
-
|
|
20
18
|
// ../../src/bootstrap/config.ts
|
|
21
19
|
import {
|
|
22
20
|
CORE_ABILITY_CHECKER_TOKEN,
|
|
@@ -30,8 +28,7 @@ import {
|
|
|
30
28
|
CORE_PUBLIC_TENANCY_TOKEN,
|
|
31
29
|
CORE_QUEUE_TOKEN,
|
|
32
30
|
CORE_TENANT_RESOLVER_TOKEN,
|
|
33
|
-
CORE_THROTTLE_QUOTA_POLICY_TOKEN
|
|
34
|
-
CORE_TOKEN_SERVICE_TOKEN
|
|
31
|
+
CORE_THROTTLE_QUOTA_POLICY_TOKEN
|
|
35
32
|
} from "@getstrata/core/contracts/serviceTokens";
|
|
36
33
|
var APP_PORT_CONFIG_KEY = "app.port";
|
|
37
34
|
var CACHE_TTL_MS_CONFIG_KEY = "cache.ttlMs";
|
|
@@ -49,93 +46,139 @@ var DEFAULT_API_TOKEN = "";
|
|
|
49
46
|
var DEFAULT_QUEUE_DRIVER = "sync";
|
|
50
47
|
|
|
51
48
|
// ../../src/bootstrap/providers/auth.ts
|
|
49
|
+
function createMetadataAuthManager(directory, options, persistRecovery) {
|
|
50
|
+
const enabled = new Set(options.mechanisms);
|
|
51
|
+
if ([...enabled].some((name) => !["api", "jwt", "basic", "session"].includes(name)))
|
|
52
|
+
throw new TypeError("Unknown authentication mechanism.");
|
|
53
|
+
const named = new Map;
|
|
54
|
+
const guards = [];
|
|
55
|
+
const add = (name, guard) => {
|
|
56
|
+
named.set(name, guard);
|
|
57
|
+
guards.push(guard);
|
|
58
|
+
return guard;
|
|
59
|
+
};
|
|
60
|
+
if (enabled.has("api")) {
|
|
61
|
+
const api = add("api", new DatabaseTokenGuard(requireAuthCapability(directory, ["resolveUserFromToken"], "API token")));
|
|
62
|
+
named.set("access_token", api);
|
|
63
|
+
}
|
|
64
|
+
if (enabled.has("jwt")) {
|
|
65
|
+
if (!options.jwtSecret)
|
|
66
|
+
throw new TypeError("Explicit JWT secret is required.");
|
|
67
|
+
add("jwt", new JwtGuard({
|
|
68
|
+
directory: requireAuthCapability(directory, ["findByIdOrThrow"], "JWT"),
|
|
69
|
+
secret: options.jwtSecret
|
|
70
|
+
}));
|
|
71
|
+
}
|
|
72
|
+
if (enabled.has("basic")) {
|
|
73
|
+
const accounts = requireAuthCapability(directory, ["findByIdOrThrow"], "Basic account");
|
|
74
|
+
const emailLookup = directory.findByEmail === undefined ? undefined : requireAuthCapability(directory, ["findByEmail"], "Basic email lookup");
|
|
75
|
+
const credentials = directory.verifyCredentials === undefined ? undefined : requireAuthCapability(directory, ["verifyCredentials"], "Basic credentials");
|
|
76
|
+
let basic;
|
|
77
|
+
if (emailLookup)
|
|
78
|
+
basic = {
|
|
79
|
+
accounts,
|
|
80
|
+
emailLookup,
|
|
81
|
+
credentials,
|
|
82
|
+
persistRecovery,
|
|
83
|
+
mfaSecrets: options.mfaSecrets
|
|
84
|
+
};
|
|
85
|
+
else if (credentials)
|
|
86
|
+
basic = { accounts, credentials, persistRecovery, mfaSecrets: options.mfaSecrets };
|
|
87
|
+
else
|
|
88
|
+
throw new TypeError("Basic authentication requires an email lookup or credential verifier.");
|
|
89
|
+
add("basic", new BasicAuthGuard(basic));
|
|
90
|
+
}
|
|
91
|
+
if (enabled.has("session")) {
|
|
92
|
+
const session = add("web", options.sessionGuard !== undefined ? requireAuthCapability(options.sessionGuard, ["authenticate"], "custom session") : new SessionGuard(requireAuthCapability(directory, ["findByIdOrThrow"], "session account"), {
|
|
93
|
+
read: options.readSession,
|
|
94
|
+
hasCredential: requireAuthCapability(options, ["hasSessionCredential"], "session presence").hasSessionCredential,
|
|
95
|
+
abilities: options.roleAbilities,
|
|
96
|
+
validity: directory.hasActiveBrowserSession === undefined ? null : requireAuthCapability(directory, ["hasActiveBrowserSession"], "session validity")
|
|
97
|
+
}));
|
|
98
|
+
named.set("session", session);
|
|
99
|
+
}
|
|
100
|
+
if (!options.production && options.allowDevHeaders)
|
|
101
|
+
guards.push(new GuestGuard({ ...options, abilities: options.abilities }));
|
|
102
|
+
const auth = new AuthManager(new CompositeGuard(guards));
|
|
103
|
+
for (const [name, guard] of named)
|
|
104
|
+
auth.registerGuard(name, guard);
|
|
105
|
+
return auth;
|
|
106
|
+
}
|
|
52
107
|
var authProvider = {
|
|
53
108
|
name: "core.auth",
|
|
54
|
-
register({ container
|
|
55
|
-
|
|
56
|
-
const apiGuard = new DatabaseTokenGuard(container);
|
|
57
|
-
const sessionGuard = new SessionGuard(container);
|
|
58
|
-
const jwtGuard = new JwtGuard(container);
|
|
59
|
-
const basicGuard = new BasicAuthGuard(container);
|
|
60
|
-
const guards = [apiGuard, jwtGuard, basicGuard, sessionGuard];
|
|
61
|
-
if (authConfig.allowDevHeaders) {
|
|
62
|
-
guards.push(new GuestGuard);
|
|
63
|
-
}
|
|
64
|
-
const auth = new AuthManager(new CompositeGuard(guards));
|
|
65
|
-
auth.registerGuard("api", apiGuard);
|
|
66
|
-
auth.registerGuard("access_token", apiGuard);
|
|
67
|
-
auth.registerGuard("jwt", jwtGuard);
|
|
68
|
-
auth.registerGuard("basic", basicGuard);
|
|
69
|
-
auth.registerGuard("web", sessionGuard);
|
|
70
|
-
auth.registerGuard("session", sessionGuard);
|
|
71
|
-
container.set(CORE_AUTH_TOKEN, auth);
|
|
109
|
+
register({ container }) {
|
|
110
|
+
container.set(CORE_AUTH_TOKEN, establishedAuthReader);
|
|
72
111
|
}
|
|
73
112
|
};
|
|
74
113
|
var auth_default = authProvider;
|
|
75
114
|
|
|
76
|
-
// ../../src/bootstrap/providers/
|
|
77
|
-
import {
|
|
115
|
+
// ../../src/bootstrap/providers/cacheProvider.ts
|
|
116
|
+
import {
|
|
117
|
+
createCacheStore,
|
|
118
|
+
snapshotCacheStoreOptions
|
|
119
|
+
} from "@getstrata/core/cache/createCacheStore";
|
|
78
120
|
import { CacheRepository } from "@getstrata/core/cache/repository";
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
121
|
+
function createCacheProvider(env) {
|
|
122
|
+
const options = snapshotCacheStoreOptions({
|
|
123
|
+
driver: env.CACHE_DRIVER ?? "array",
|
|
124
|
+
ttlMs: Number(env.CACHE_TTL_MS ?? "3600000"),
|
|
125
|
+
maxEntries: Number(env.CACHE_MAX_ENTRIES ?? "100"),
|
|
126
|
+
redisUrl: env.REDIS_URL || undefined,
|
|
127
|
+
namespace: `${env.APP_KEY_PREFIX?.trim() || "strata"}:cache:v3:`
|
|
128
|
+
});
|
|
129
|
+
return Object.freeze({
|
|
130
|
+
name: "core.cache",
|
|
131
|
+
register({
|
|
132
|
+
container,
|
|
133
|
+
dependencies,
|
|
134
|
+
onCleanup
|
|
135
|
+
}) {
|
|
136
|
+
container.singleton(CORE_CACHE_TOKEN, () => {
|
|
137
|
+
const cache = new CacheRepository(createCacheStore(options));
|
|
138
|
+
onCleanup(() => cache.close());
|
|
139
|
+
return cache;
|
|
88
140
|
});
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
dependencies.cache = container.resolve(CORE_CACHE_TOKEN);
|
|
94
|
-
}
|
|
95
|
-
};
|
|
96
|
-
var cache_default = cacheProvider;
|
|
141
|
+
dependencies.cache = container.resolve(CORE_CACHE_TOKEN);
|
|
142
|
+
}
|
|
143
|
+
});
|
|
144
|
+
}
|
|
97
145
|
|
|
98
146
|
// ../../src/bootstrap/providers/config.ts
|
|
99
147
|
import { validateEnv } from "@getstrata/core/config/envSchema";
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
apiPrefix: process.env.API_PREFIX ?? "/api/v1"
|
|
108
|
-
};
|
|
148
|
+
import { CORE_JSON_RESPONSE_POLICY_TOKEN } from "@getstrata/core/contracts/serviceTokens";
|
|
149
|
+
import { resolveMaxBodyBytes } from "@getstrata/core/http/bodySizeLimitMiddleware";
|
|
150
|
+
import { resolveCorsConfig } from "@getstrata/core/http/corsMiddleware";
|
|
151
|
+
import { resolveMaxUploadBytes } from "@getstrata/core/http/uploads";
|
|
152
|
+
import { envFlagEnabled, isProductionEnv } from "@getstrata/core/runtime/appEnv";
|
|
153
|
+
import { parseFrontendMode } from "@getstrata/core/runtime/frontendMode";
|
|
154
|
+
import { resolveDefaultTokenExpiryDays } from "@getstrata/core/security/tokenExpiry";
|
|
109
155
|
|
|
110
156
|
// ../../src/core/queue/queueConfig.ts
|
|
111
|
-
function
|
|
112
|
-
const
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
157
|
+
function snapshotQueueRetryPolicy(policy) {
|
|
158
|
+
const { maxAttempts, backoffMs } = policy;
|
|
159
|
+
if (!Number.isSafeInteger(maxAttempts) || maxAttempts < 1)
|
|
160
|
+
throw new TypeError("QUEUE_MAX_ATTEMPTS must be a positive safe integer.");
|
|
161
|
+
if (!Number.isSafeInteger(backoffMs) || backoffMs < 0 || backoffMs > 2147483647)
|
|
162
|
+
throw new TypeError("QUEUE_BACKOFF_MS must be a non-negative integer within the timer range.");
|
|
163
|
+
return Object.freeze({ maxAttempts, backoffMs });
|
|
164
|
+
}
|
|
165
|
+
function resolveQueueConfig(env = process.env) {
|
|
166
|
+
const driver = env.QUEUE_DRIVER ?? "sync";
|
|
167
|
+
if (!["sync", "async", "redis"].includes(driver))
|
|
168
|
+
throw new TypeError("Unknown queue driver.");
|
|
169
|
+
const policy = snapshotQueueRetryPolicy({
|
|
170
|
+
maxAttempts: Number(env.QUEUE_MAX_ATTEMPTS ?? "3"),
|
|
171
|
+
backoffMs: Number(env.QUEUE_BACKOFF_MS ?? "1000")
|
|
172
|
+
});
|
|
173
|
+
return Object.freeze({ driver, ...policy });
|
|
120
174
|
}
|
|
121
|
-
var queueConfig = {
|
|
122
|
-
get driver() {
|
|
123
|
-
return resolveQueueConfig().driver;
|
|
124
|
-
},
|
|
125
|
-
get maxAttempts() {
|
|
126
|
-
return resolveQueueConfig().maxAttempts;
|
|
127
|
-
},
|
|
128
|
-
get backoffMs() {
|
|
129
|
-
return resolveQueueConfig().backoffMs;
|
|
130
|
-
}
|
|
131
|
-
};
|
|
132
175
|
// ../../src/bootstrap/env.ts
|
|
133
176
|
import { defineEnvSchema } from "@getstrata/core/config/envSchema";
|
|
134
177
|
import { DEFAULT_SPA_PREFIX, FRONTEND_MODE_PATTERN } from "@getstrata/core/runtime/frontendMode";
|
|
135
178
|
var appEnvSchema = defineEnvSchema({
|
|
136
179
|
DATABASE_URL: {
|
|
137
180
|
required: true,
|
|
138
|
-
pattern: /^(postgres(ql)?|mysql
|
|
181
|
+
pattern: /^(?:(?:postgres(?:ql)?|mysql):\/\/\S+|sqlite:(?:\/\/)?\S+)$/i
|
|
139
182
|
},
|
|
140
183
|
PORT: {
|
|
141
184
|
integer: true,
|
|
@@ -242,52 +285,139 @@ var appEnvSchema = defineEnvSchema({
|
|
|
242
285
|
}
|
|
243
286
|
});
|
|
244
287
|
|
|
245
|
-
// ../../src/bootstrap/
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
288
|
+
// ../../src/bootstrap/rateLimit.ts
|
|
289
|
+
var LOCAL_LOGIN_RATE_LIMIT = {
|
|
290
|
+
maxAttempts: 100,
|
|
291
|
+
decaySeconds: 60
|
|
292
|
+
};
|
|
293
|
+
var PRODUCTION_LOGIN_RATE_LIMIT = {
|
|
294
|
+
maxAttempts: 5,
|
|
295
|
+
decaySeconds: 900
|
|
296
|
+
};
|
|
297
|
+
function parsePositiveInt(value, fallback) {
|
|
298
|
+
const parsed = Number(value);
|
|
299
|
+
if (!Number.isFinite(parsed) || parsed <= 0) {
|
|
300
|
+
return fallback;
|
|
251
301
|
}
|
|
252
|
-
return parsed;
|
|
302
|
+
return Math.trunc(parsed);
|
|
253
303
|
}
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
const env = validateEnv(appEnvSchema);
|
|
258
|
-
container.set(CORE_CONFIG_TOKEN, config);
|
|
259
|
-
if (process.env.CSRF_TARGET_ORIGIN !== undefined)
|
|
260
|
-
config.set(CSRF_TARGET_ORIGIN_CONFIG_KEY, process.env.CSRF_TARGET_ORIGIN);
|
|
261
|
-
config.set(DATABASE_URL_CONFIG_KEY, env.DATABASE_URL);
|
|
262
|
-
config.set(APP_PORT_CONFIG_KEY, parseInteger(env.PORT ?? String(DEFAULT_APP_PORT), "PORT", 1));
|
|
263
|
-
config.set(CACHE_TTL_MS_CONFIG_KEY, parseInteger(env.CACHE_TTL_MS ?? String(DEFAULT_CACHE_TTL_MS), "CACHE_TTL_MS", 0));
|
|
264
|
-
config.set(CACHE_MAX_ENTRIES_CONFIG_KEY, parseInteger(env.CACHE_MAX_ENTRIES ?? String(DEFAULT_CACHE_MAX_ENTRIES), "CACHE_MAX_ENTRIES", 1));
|
|
265
|
-
config.set(CACHE_DRIVER_CONFIG_KEY, env.CACHE_DRIVER ?? DEFAULT_CACHE_DRIVER);
|
|
266
|
-
config.set(REDIS_URL_CONFIG_KEY, env.REDIS_URL ?? "");
|
|
267
|
-
config.set("app.env", appConfig.env);
|
|
268
|
-
config.set("app.debug", appConfig.debug);
|
|
269
|
-
config.set("app.url", appConfig.url);
|
|
270
|
-
config.set("app.apiPrefix", appConfig.apiPrefix);
|
|
271
|
-
config.set("auth.allowDevHeaders", authConfig.allowDevHeaders);
|
|
272
|
-
config.set("queue.driver", queueConfig.driver);
|
|
273
|
-
config.set("queue.maxAttempts", queueConfig.maxAttempts);
|
|
274
|
-
config.set("queue.backoffMs", queueConfig.backoffMs);
|
|
304
|
+
function parseWindowSeconds(secondsValue, msValue, fallback) {
|
|
305
|
+
if (secondsValue !== undefined && secondsValue.trim() !== "") {
|
|
306
|
+
return parsePositiveInt(secondsValue, fallback);
|
|
275
307
|
}
|
|
276
|
-
|
|
277
|
-
|
|
308
|
+
if (msValue !== undefined && msValue.trim() !== "") {
|
|
309
|
+
const parsedMs = Number(msValue);
|
|
310
|
+
if (Number.isFinite(parsedMs) && parsedMs > 0) {
|
|
311
|
+
return Math.max(1, Math.trunc(parsedMs / 1000));
|
|
312
|
+
}
|
|
313
|
+
}
|
|
314
|
+
return fallback;
|
|
315
|
+
}
|
|
316
|
+
function resolveLoginRateLimit(env = {}) {
|
|
317
|
+
const defaults = env.APP_ENV === "local" ? LOCAL_LOGIN_RATE_LIMIT : PRODUCTION_LOGIN_RATE_LIMIT;
|
|
318
|
+
return {
|
|
319
|
+
maxAttempts: parsePositiveInt(env.LOGIN_RATE_LIMIT_PER_WINDOW, defaults.maxAttempts),
|
|
320
|
+
decaySeconds: parseWindowSeconds(env.LOGIN_RATE_LIMIT_WINDOW_SECONDS, env.LOGIN_RATE_LIMIT_WINDOW_MS, defaults.decaySeconds)
|
|
321
|
+
};
|
|
322
|
+
}
|
|
323
|
+
function resolveRegisterRateLimit(env = {}) {
|
|
324
|
+
const defaults = env.APP_ENV === "local" ? { maxAttempts: 100, decaySeconds: 60 } : { maxAttempts: 10, decaySeconds: 60 };
|
|
325
|
+
return {
|
|
326
|
+
maxAttempts: parsePositiveInt(env.REGISTER_RATE_LIMIT_PER_WINDOW, defaults.maxAttempts),
|
|
327
|
+
decaySeconds: parseWindowSeconds(env.REGISTER_RATE_LIMIT_WINDOW_SECONDS, env.REGISTER_RATE_LIMIT_WINDOW_MS, defaults.decaySeconds)
|
|
328
|
+
};
|
|
329
|
+
}
|
|
278
330
|
|
|
279
|
-
// ../../src/bootstrap/providers/
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
331
|
+
// ../../src/bootstrap/providers/config.ts
|
|
332
|
+
function resolveHttpResponsePolicy(source) {
|
|
333
|
+
const cors = Object.freeze({
|
|
334
|
+
allowedOrigins: Object.freeze((source.CORS_ALLOWED_ORIGINS ?? (source.APP_URL?.trim() || "http://localhost:3000").replace(/\/$/, "")).split(",").map((origin) => origin.trim()).filter(Boolean)),
|
|
335
|
+
additionalAllowedHeaders: Object.freeze(source.CORS_ADDITIONAL_ALLOWED_HEADERS?.trim() ? source.CORS_ADDITIONAL_ALLOWED_HEADERS.split(",").map((name) => name.trim()) : [])
|
|
336
|
+
});
|
|
337
|
+
resolveCorsConfig(cors);
|
|
338
|
+
const maxAttempts = Number(source.RATE_LIMIT_PER_MINUTE ?? "120");
|
|
339
|
+
return Object.freeze({
|
|
340
|
+
cors,
|
|
341
|
+
securityHeaders: Object.freeze({
|
|
342
|
+
frontendMode: parseFrontendMode(source.FRONTEND_MODE),
|
|
343
|
+
production: isProductionEnv(source)
|
|
344
|
+
}),
|
|
345
|
+
maxBodyBytes: resolveMaxBodyBytes(source.MAX_REQUEST_BODY_BYTES),
|
|
346
|
+
rateLimitPerMinute: Number.isFinite(maxAttempts) ? maxAttempts : 120,
|
|
347
|
+
namespace: source.APP_KEY_PREFIX?.trim() || "strata",
|
|
348
|
+
trustForwardedFor: source.TRUST_FORWARDED_FOR === "true",
|
|
349
|
+
loginRateLimit: Object.freeze(resolveLoginRateLimit({ APP_ENV: "local", ...source })),
|
|
350
|
+
registerRateLimit: Object.freeze(resolveRegisterRateLimit({ APP_ENV: "local", ...source }))
|
|
351
|
+
});
|
|
352
|
+
}
|
|
353
|
+
function createConfigProvider(input) {
|
|
354
|
+
const source = Object.freeze({ ...input });
|
|
355
|
+
const env = validateEnv(appEnvSchema, source);
|
|
356
|
+
const queue = resolveQueueConfig(env);
|
|
357
|
+
const values = Object.freeze({
|
|
358
|
+
[DATABASE_URL_CONFIG_KEY]: env.DATABASE_URL,
|
|
359
|
+
[APP_PORT_CONFIG_KEY]: Number(env.PORT),
|
|
360
|
+
[CACHE_TTL_MS_CONFIG_KEY]: Number(env.CACHE_TTL_MS),
|
|
361
|
+
[CACHE_MAX_ENTRIES_CONFIG_KEY]: Number(env.CACHE_MAX_ENTRIES),
|
|
362
|
+
[CACHE_DRIVER_CONFIG_KEY]: env.CACHE_DRIVER,
|
|
363
|
+
[REDIS_URL_CONFIG_KEY]: env.REDIS_URL,
|
|
364
|
+
"http.responsePolicy": resolveHttpResponsePolicy({ ...source, APP_URL: env.APP_URL }),
|
|
365
|
+
"http.features": Object.freeze({
|
|
366
|
+
emailVerificationRequired: source.FEATURE_EMAIL_VERIFICATION === "true",
|
|
367
|
+
viewsEnabled: ["server-htmx", "hybrid"].includes(source.FRONTEND_MODE ?? "api"),
|
|
368
|
+
publicReadsEnabled: source.FEATURE_PUBLIC_READS === "true",
|
|
369
|
+
etagEnabled: source.FEATURE_ETAG !== "false"
|
|
370
|
+
}),
|
|
371
|
+
"http.uploadPolicy": Object.freeze({
|
|
372
|
+
maxBytes: resolveMaxUploadBytes(source.MAX_UPLOAD_BYTES?.trim() ?? source.MAX_REQUEST_BODY_BYTES?.trim()),
|
|
373
|
+
allowUnknownMime: envFlagEnabled(source.UPLOAD_ALLOW_UNKNOWN_MIME)
|
|
374
|
+
}),
|
|
375
|
+
"auth.defaultTokenExpiryDays": resolveDefaultTokenExpiryDays(source.API_TOKEN_DEFAULT_EXPIRY_DAYS),
|
|
376
|
+
"app.name": source.APP_NAME?.trim() || "Strata",
|
|
377
|
+
"app.env": env.APP_ENV,
|
|
378
|
+
"app.debug": source.APP_DEBUG === "true",
|
|
379
|
+
"app.url": env.APP_URL,
|
|
380
|
+
"app.apiPrefix": env.API_PREFIX,
|
|
381
|
+
"auth.allowDevHeaders": envFlagEnabled(env.AUTH_DEV_HEADERS),
|
|
382
|
+
"queue.driver": queue.driver,
|
|
383
|
+
"queue.maxAttempts": queue.maxAttempts,
|
|
384
|
+
"queue.backoffMs": queue.backoffMs,
|
|
385
|
+
...source.CSRF_TARGET_ORIGIN !== undefined ? { [CSRF_TARGET_ORIGIN_CONFIG_KEY]: source.CSRF_TARGET_ORIGIN } : {}
|
|
386
|
+
});
|
|
387
|
+
return Object.freeze({
|
|
388
|
+
name: "core.config",
|
|
389
|
+
register({ container, config }) {
|
|
390
|
+
container.set(CORE_CONFIG_TOKEN, config);
|
|
391
|
+
container.set(CORE_JSON_RESPONSE_POLICY_TOKEN, Object.freeze({ etagEnabled: source.FEATURE_ETAG !== "false" }));
|
|
392
|
+
for (const [key, value] of Object.entries(values))
|
|
393
|
+
config.set(key, value);
|
|
394
|
+
}
|
|
395
|
+
});
|
|
396
|
+
}
|
|
397
|
+
|
|
398
|
+
// ../../src/bootstrap/providers/policy.ts
|
|
399
|
+
import { PolicyGate } from "@getstrata/core/auth/policy";
|
|
400
|
+
var policyProvider = {
|
|
401
|
+
name: "core.policy",
|
|
283
402
|
register({ container }) {
|
|
284
|
-
container.set(
|
|
403
|
+
container.set(CORE_POLICY_GATE_TOKEN, new PolicyGate);
|
|
285
404
|
}
|
|
286
405
|
};
|
|
287
|
-
var
|
|
406
|
+
var policy_default = policyProvider;
|
|
288
407
|
|
|
289
|
-
// ../../src/bootstrap/
|
|
408
|
+
// ../../src/bootstrap/providers/queue.ts
|
|
409
|
+
import { createAuditExporter } from "@getstrata/core/audit/exportAuditLogs";
|
|
410
|
+
import {
|
|
411
|
+
createAppQueue,
|
|
412
|
+
createSystemQueueServices,
|
|
413
|
+
FAILED_JOB_SERVICE_TOKEN
|
|
414
|
+
} from "@getstrata/core/queue/createAppQueue";
|
|
415
|
+
import { JobRegistry, QUEUE_JOB_REGISTRY_TOKEN } from "@getstrata/core/queue/jobRegistry";
|
|
416
|
+
import { resolveQueueConfig as resolveQueueConfig2, resolveQueueRuntimeConfig } from "@getstrata/core/queue/queueConfig";
|
|
417
|
+
|
|
418
|
+
// ../../src/bootstrap/discoverJobs.ts
|
|
290
419
|
import { join as join2, resolve } from "path";
|
|
420
|
+
import { Job } from "@getstrata/core/queue";
|
|
291
421
|
|
|
292
422
|
// ../../src/bootstrap/infrastructureDiscovery.ts
|
|
293
423
|
import { readdir } from "fs/promises";
|
|
@@ -338,353 +468,21 @@ async function importInfrastructure(file) {
|
|
|
338
468
|
}
|
|
339
469
|
}
|
|
340
470
|
|
|
341
|
-
// ../../src/bootstrap/
|
|
342
|
-
var
|
|
343
|
-
function state() {
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
async function load(options) {
|
|
349
|
-
const listeners = new Set;
|
|
350
|
-
const add = (value, location) => {
|
|
351
|
-
if (typeof value !== "function")
|
|
352
|
-
throw new TypeError(`Invalid listener registrar at ${location}: expected a default function.`);
|
|
353
|
-
listeners.add(value);
|
|
354
|
-
};
|
|
355
|
-
if (options.manifest)
|
|
356
|
-
for (const [index, value] of options.manifest.entries())
|
|
357
|
-
add(value, `listener manifest[${index}]`);
|
|
358
|
-
else
|
|
359
|
-
for (const file of await infrastructureFiles(options.directory ?? join2(process.cwd(), "src", "listeners"), options.exclude)) {
|
|
360
|
-
const exports = await importInfrastructure(file);
|
|
361
|
-
const value = exports.default;
|
|
362
|
-
add(value && typeof value === "object" && "default" in value ? value.default : value, file);
|
|
363
|
-
}
|
|
364
|
-
return [...listeners];
|
|
365
|
-
}
|
|
366
|
-
function discoverListeners(options = {}) {
|
|
367
|
-
const cache = state().loads;
|
|
368
|
-
const key = options.manifest ?? JSON.stringify([
|
|
369
|
-
resolve(options.directory ?? join2(process.cwd(), "src", "listeners")),
|
|
370
|
-
[...options.exclude ?? []].sort()
|
|
371
|
-
]);
|
|
372
|
-
const existing = cache.get(key);
|
|
373
|
-
if (existing)
|
|
374
|
-
return existing;
|
|
375
|
-
const pending = load(options).catch((error) => {
|
|
376
|
-
if (cache.get(key) === pending)
|
|
377
|
-
cache.delete(key);
|
|
378
|
-
throw error;
|
|
379
|
-
});
|
|
380
|
-
cache.set(key, pending);
|
|
381
|
-
return pending;
|
|
382
|
-
}
|
|
383
|
-
function resetDiscoverListenersForTests() {
|
|
384
|
-
state().loads = new Map;
|
|
385
|
-
}
|
|
386
|
-
|
|
387
|
-
// ../../src/bootstrap/listeners/invalidateCacheOnModelWrite.ts
|
|
388
|
-
import { eventBus as eventBus2, modelEventName } from "@getstrata/core/events";
|
|
389
|
-
import { InvalidateCacheTagsJob } from "@getstrata/core/jobs/invalidateCacheTagsJob";
|
|
390
|
-
import { createTrackedJob } from "@getstrata/core/queue/createAppQueue";
|
|
391
|
-
|
|
392
|
-
// ../../src/bootstrap/applicationRegistry.ts
|
|
393
|
-
import {
|
|
394
|
-
resolveApplicationAuth,
|
|
395
|
-
resolveApplicationCache,
|
|
396
|
-
resolveApplicationConfig,
|
|
397
|
-
resolveApplicationDependencies,
|
|
398
|
-
resolveApplicationEventBus,
|
|
399
|
-
resolveApplicationLogger,
|
|
400
|
-
resolveApplicationPolicyGate,
|
|
401
|
-
resolveApplicationQueue,
|
|
402
|
-
setActiveApplicationContext
|
|
403
|
-
} from "@getstrata/core/runtime/applicationRegistry";
|
|
404
|
-
|
|
405
|
-
// ../../src/bootstrap/discoverModules.ts
|
|
406
|
-
import { readdir as readdir2 } from "fs/promises";
|
|
407
|
-
import { join as join3, resolve as resolve2 } from "path";
|
|
408
|
-
var KEY2 = Symbol.for("@getstrata/discoverModulesState");
|
|
409
|
-
function state2() {
|
|
410
|
-
const globals = globalThis;
|
|
411
|
-
globals[KEY2] ??= { appModules: [] };
|
|
412
|
-
return globals[KEY2];
|
|
413
|
-
}
|
|
414
|
-
function configureModulesDirectory(modulesDir) {
|
|
415
|
-
const current = state2();
|
|
416
|
-
const directory = resolve2(modulesDir);
|
|
417
|
-
if (current.configuredModulesDir !== directory || current.configuredManifest) {
|
|
418
|
-
current.appModules.length = 0;
|
|
419
|
-
current.modulesReady = undefined;
|
|
420
|
-
current.source = undefined;
|
|
421
|
-
}
|
|
422
|
-
current.configuredManifest = undefined;
|
|
423
|
-
current.configuredModulesDir = directory;
|
|
424
|
-
}
|
|
425
|
-
function configureModulesManifest(manifest) {
|
|
426
|
-
const current = state2();
|
|
427
|
-
if (current.configuredManifest !== manifest) {
|
|
428
|
-
current.appModules.length = 0;
|
|
429
|
-
current.modulesReady = undefined;
|
|
430
|
-
current.source = undefined;
|
|
431
|
-
}
|
|
432
|
-
current.configuredManifest = manifest;
|
|
433
|
-
}
|
|
434
|
-
function validateModule(value, location) {
|
|
435
|
-
if (!value || typeof value !== "object" || Array.isArray(value))
|
|
436
|
-
throw new TypeError(`Invalid application module at ${location}.`);
|
|
437
|
-
const module = value;
|
|
438
|
-
if (typeof module.name !== "string" || !module.name.trim())
|
|
439
|
-
throw new TypeError(`Invalid module name at ${location}.`);
|
|
440
|
-
if (module.order !== undefined && (typeof module.order !== "number" || !Number.isFinite(module.order)))
|
|
441
|
-
throw new TypeError(`Invalid module order at ${location}.`);
|
|
442
|
-
for (const hook of ["routes", "webRoutes"])
|
|
443
|
-
if (module[hook] !== undefined && typeof module[hook] !== "function")
|
|
444
|
-
throw new TypeError(`Invalid ${hook} at ${location}.`);
|
|
445
|
-
if (module.providers !== undefined) {
|
|
446
|
-
if (!Array.isArray(module.providers))
|
|
447
|
-
throw new TypeError(`Invalid providers at ${location}.`);
|
|
448
|
-
for (const provider of module.providers) {
|
|
449
|
-
if (!provider || typeof provider.name !== "string" || !provider.name.trim() || provider.register !== undefined && typeof provider.register !== "function" || provider.boot !== undefined && typeof provider.boot !== "function")
|
|
450
|
-
throw new TypeError(`Invalid provider at ${location}.`);
|
|
451
|
-
}
|
|
452
|
-
}
|
|
453
|
-
}
|
|
454
|
-
async function load2(options) {
|
|
455
|
-
const manifest = options.manifest ?? (options.modulesDir === undefined ? state2().configuredManifest : undefined);
|
|
456
|
-
const entries = [];
|
|
457
|
-
if (manifest)
|
|
458
|
-
for (const [index, value] of manifest.entries())
|
|
459
|
-
entries.push({ value, location: `module manifest[${index}]` });
|
|
460
|
-
else {
|
|
461
|
-
const directory = options.modulesDir ?? state2().configuredModulesDir;
|
|
462
|
-
if (!directory)
|
|
463
|
-
throw new Error("configureModulesDirectory() or configureModulesManifest() must be called before discovering modules.");
|
|
464
|
-
let folders;
|
|
465
|
-
try {
|
|
466
|
-
folders = await readdir2(directory, { withFileTypes: true });
|
|
467
|
-
} catch (error) {
|
|
468
|
-
if (error.code === "ENOENT")
|
|
469
|
-
return [];
|
|
470
|
-
throw error;
|
|
471
|
-
}
|
|
472
|
-
const excluded = new Set(options.exclude ?? []);
|
|
473
|
-
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)) {
|
|
474
|
-
const path = join3(directory, folder.name);
|
|
475
|
-
const files = await readdir2(path);
|
|
476
|
-
const candidates = files.filter((file) => /^index\.(ts|js|mts|mjs)$/.test(file));
|
|
477
|
-
if (candidates.length !== 1)
|
|
478
|
-
throw new Error(`Expected one module entrypoint at ${path}; found ${candidates.length}.`);
|
|
479
|
-
const file = join3(path, candidates[0]);
|
|
480
|
-
const exports = await importInfrastructure(file);
|
|
481
|
-
entries.push({ value: exports.default, location: file });
|
|
482
|
-
}
|
|
483
|
-
}
|
|
484
|
-
const names = new Map;
|
|
485
|
-
const modules = [];
|
|
486
|
-
for (const { value, location } of entries) {
|
|
487
|
-
validateModule(value, location);
|
|
488
|
-
const previous = names.get(value.name);
|
|
489
|
-
if (previous)
|
|
490
|
-
throw new Error(`Duplicate module "${value.name}" at ${location}; first declared at ${previous}.`);
|
|
491
|
-
names.set(value.name, location);
|
|
492
|
-
modules.push(value);
|
|
471
|
+
// ../../src/bootstrap/discoverJobs.ts
|
|
472
|
+
var states = new WeakMap;
|
|
473
|
+
function state(registry) {
|
|
474
|
+
let value = states.get(registry);
|
|
475
|
+
if (!value) {
|
|
476
|
+
value = { loads: new Map, registered: new Map };
|
|
477
|
+
states.set(registry, value);
|
|
493
478
|
}
|
|
494
|
-
return modules.sort((left, right) => (left.order ?? 100) - (right.order ?? 100));
|
|
495
|
-
}
|
|
496
|
-
function ensureModulesLoaded(options = {}) {
|
|
497
|
-
const current = state2();
|
|
498
|
-
const key = options.manifest ?? (options.modulesDir === undefined ? current.configuredManifest : undefined) ?? JSON.stringify([
|
|
499
|
-
options.modulesDir ? resolve2(options.modulesDir) : current.configuredModulesDir,
|
|
500
|
-
[...options.exclude ?? []].sort()
|
|
501
|
-
]);
|
|
502
|
-
if (current.modulesReady && current.source === key)
|
|
503
|
-
return current.modulesReady;
|
|
504
|
-
current.appModules.length = 0;
|
|
505
|
-
current.source = key;
|
|
506
|
-
const pending = load2(options).then((modules) => {
|
|
507
|
-
if (current.modulesReady !== pending)
|
|
508
|
-
return modules;
|
|
509
|
-
current.appModules.splice(0, current.appModules.length, ...modules);
|
|
510
|
-
return current.appModules;
|
|
511
|
-
}).catch((error) => {
|
|
512
|
-
if (current.modulesReady === pending)
|
|
513
|
-
current.modulesReady = undefined;
|
|
514
|
-
throw error;
|
|
515
|
-
});
|
|
516
|
-
current.modulesReady = pending;
|
|
517
|
-
return pending;
|
|
518
|
-
}
|
|
519
|
-
function discoverModules() {
|
|
520
|
-
return state2().appModules;
|
|
521
|
-
}
|
|
522
|
-
function resetDiscoverModulesForTests() {
|
|
523
|
-
const current = state2();
|
|
524
|
-
current.configuredModulesDir = undefined;
|
|
525
|
-
current.configuredManifest = undefined;
|
|
526
|
-
current.appModules.length = 0;
|
|
527
|
-
current.modulesReady = undefined;
|
|
528
|
-
current.source = undefined;
|
|
529
|
-
}
|
|
530
|
-
|
|
531
|
-
// ../../src/bootstrap/cache/modelCacheTags.ts
|
|
532
|
-
function cacheTagsForModelWrite(tableName, action) {
|
|
533
|
-
const module = discoverModules().find((entry) => entry.tableName === tableName);
|
|
534
|
-
const baseTags = module?.cacheTags ?? [`${tableName}s`];
|
|
535
|
-
const isDelete = action === "deleted" || action === "force-deleted";
|
|
536
|
-
const extraTags = isDelete ? module?.cacheDeleteExtraTags ?? [] : [];
|
|
537
|
-
return [...new Set([...baseTags, ...extraTags])];
|
|
538
|
-
}
|
|
539
|
-
function discoverModelTableNames() {
|
|
540
|
-
return discoverModules().map((module) => module.tableName).filter((tableName) => tableName !== undefined);
|
|
541
|
-
}
|
|
542
|
-
|
|
543
|
-
// ../../src/bootstrap/listeners/invalidateCacheOnModelWrite.ts
|
|
544
|
-
var MODEL_WRITE_ACTIONS = ["created", "updated", "deleted", "restored", "force-deleted"];
|
|
545
|
-
var CACHE_EVENT = "strata.cache.invalidate-tags";
|
|
546
|
-
var STATE_KEY = Symbol.for("@getstrata/modelCacheInvalidationRegistrations");
|
|
547
|
-
function registrations() {
|
|
548
|
-
const global = globalThis;
|
|
549
|
-
global[STATE_KEY] ??= new WeakMap;
|
|
550
|
-
return global[STATE_KEY];
|
|
551
|
-
}
|
|
552
|
-
function requireCacheTags(value) {
|
|
553
|
-
if (!Array.isArray(value) || !value.length || value.length > 128 || !value.every((tag) => typeof tag === "string" && tag.length > 0 && tag.length <= 256))
|
|
554
|
-
throw new Error("Invalid durable cache invalidation payload.");
|
|
555
479
|
return value;
|
|
556
480
|
}
|
|
557
|
-
function createModelCacheInvalidationListener(resolveCache = resolveApplicationCache) {
|
|
558
|
-
return {
|
|
559
|
-
name: "strata.cache.invalidate-tags.v1",
|
|
560
|
-
event: CACHE_EVENT,
|
|
561
|
-
async handle(event, { signal }) {
|
|
562
|
-
const payload = event.payload;
|
|
563
|
-
if (event.version !== 1)
|
|
564
|
-
throw new Error("Invalid durable cache invalidation version.");
|
|
565
|
-
const tags = requireCacheTags(payload?.tags);
|
|
566
|
-
signal.throwIfAborted();
|
|
567
|
-
await new InvalidateCacheTagsJob(resolveCache()).handle({ tags });
|
|
568
|
-
signal.throwIfAborted();
|
|
569
|
-
}
|
|
570
|
-
};
|
|
571
|
-
}
|
|
572
|
-
function registerInvalidateCacheOnModelWriteListeners(bus = eventBus2, options = {}) {
|
|
573
|
-
if (options.outbox && !options.outbox.hasListener("strata.cache.invalidate-tags.v1", CACHE_EVENT))
|
|
574
|
-
throw new Error("The application outbox must include createModelCacheInvalidationListener().");
|
|
575
|
-
const writes = discoverModelTableNames().flatMap((tableName) => MODEL_WRITE_ACTIONS.map((action) => ({
|
|
576
|
-
tableName,
|
|
577
|
-
action,
|
|
578
|
-
tags: cacheTagsForModelWrite(tableName, action)
|
|
579
|
-
})));
|
|
580
|
-
if (options.outbox) {
|
|
581
|
-
for (const write of writes)
|
|
582
|
-
if (write.tags.length)
|
|
583
|
-
requireCacheTags(write.tags);
|
|
584
|
-
}
|
|
585
|
-
const state = registrations();
|
|
586
|
-
const previous = state.get(bus);
|
|
587
|
-
if (previous?.durable && !options.outbox)
|
|
588
|
-
return () => {};
|
|
589
|
-
previous?.suspend();
|
|
590
|
-
const unsubscribe = [];
|
|
591
|
-
const subscribe = [];
|
|
592
|
-
const registration = {
|
|
593
|
-
durable: !!options.outbox,
|
|
594
|
-
suspend() {
|
|
595
|
-
for (const stop of unsubscribe.splice(0))
|
|
596
|
-
stop();
|
|
597
|
-
},
|
|
598
|
-
resume() {
|
|
599
|
-
for (const start of subscribe)
|
|
600
|
-
unsubscribe.push(start());
|
|
601
|
-
state.set(bus, registration);
|
|
602
|
-
},
|
|
603
|
-
dispose() {
|
|
604
|
-
if (state.get(bus) !== registration)
|
|
605
|
-
return;
|
|
606
|
-
registration.suspend();
|
|
607
|
-
if (previous)
|
|
608
|
-
previous.resume();
|
|
609
|
-
else
|
|
610
|
-
state.delete(bus);
|
|
611
|
-
}
|
|
612
|
-
};
|
|
613
|
-
for (const { tableName, action, tags: durableTags } of writes) {
|
|
614
|
-
const event = modelEventName(tableName, action);
|
|
615
|
-
if (options.outbox) {
|
|
616
|
-
if (!durableTags.length)
|
|
617
|
-
continue;
|
|
618
|
-
const outbox = options.outbox;
|
|
619
|
-
subscribe.push(() => bus.listenTransactional(event, async () => {
|
|
620
|
-
await outbox.publish(CACHE_EVENT, { tags: durableTags });
|
|
621
|
-
}));
|
|
622
|
-
} else {
|
|
623
|
-
subscribe.push(() => bus.listen(event, async () => {
|
|
624
|
-
const tags = cacheTagsForModelWrite(tableName, action);
|
|
625
|
-
if (!tags.length)
|
|
626
|
-
return;
|
|
627
|
-
let cache;
|
|
628
|
-
let queue;
|
|
629
|
-
try {
|
|
630
|
-
cache = resolveApplicationCache();
|
|
631
|
-
queue = resolveApplicationQueue();
|
|
632
|
-
} catch {
|
|
633
|
-
return;
|
|
634
|
-
}
|
|
635
|
-
const job = createTrackedJob("cache.invalidate-tags", new InvalidateCacheTagsJob(cache));
|
|
636
|
-
await queue.dispatch(job, { tags });
|
|
637
|
-
}));
|
|
638
|
-
}
|
|
639
|
-
}
|
|
640
|
-
registration.resume();
|
|
641
|
-
return registration.dispose;
|
|
642
|
-
}
|
|
643
|
-
|
|
644
|
-
// ../../src/bootstrap/providers/listeners.ts
|
|
645
|
-
var listenersProvider = {
|
|
646
|
-
name: "core.listeners",
|
|
647
|
-
async boot({ onCleanup }) {
|
|
648
|
-
onCleanup(registerInvalidateCacheOnModelWriteListeners());
|
|
649
|
-
for (const registerListener of await discoverListeners()) {
|
|
650
|
-
await registerListener();
|
|
651
|
-
}
|
|
652
|
-
}
|
|
653
|
-
};
|
|
654
|
-
var listeners_default = listenersProvider;
|
|
655
|
-
|
|
656
|
-
// ../../src/bootstrap/providers/policy.ts
|
|
657
|
-
import { PolicyGate } from "@getstrata/core/auth/policy";
|
|
658
|
-
var policyProvider = {
|
|
659
|
-
name: "core.policy",
|
|
660
|
-
register({ container }) {
|
|
661
|
-
container.set(CORE_POLICY_GATE_TOKEN, new PolicyGate);
|
|
662
|
-
}
|
|
663
|
-
};
|
|
664
|
-
var policy_default = policyProvider;
|
|
665
|
-
|
|
666
|
-
// ../../src/bootstrap/providers/queue.ts
|
|
667
|
-
import {
|
|
668
|
-
createAppQueue,
|
|
669
|
-
createFailedJobService,
|
|
670
|
-
FAILED_JOB_SERVICE_TOKEN
|
|
671
|
-
} from "@getstrata/core/queue/createAppQueue";
|
|
672
|
-
|
|
673
|
-
// ../../src/bootstrap/discoverJobs.ts
|
|
674
|
-
import { join as join4, resolve as resolve3 } from "path";
|
|
675
|
-
import { Job } from "@getstrata/core/queue";
|
|
676
|
-
import { jobRegistry } from "@getstrata/core/queue/jobRegistry";
|
|
677
|
-
var KEY3 = Symbol.for("@getstrata/discoverJobsState");
|
|
678
|
-
function state3() {
|
|
679
|
-
const globals = globalThis;
|
|
680
|
-
globals[KEY3] ??= { loads: new Map, registered: new Map };
|
|
681
|
-
return globals[KEY3];
|
|
682
|
-
}
|
|
683
481
|
function validateClass(value, location) {
|
|
684
482
|
if (typeof value !== "function" || typeof value.jobName !== "string" || !value.jobName.trim() || !(value.prototype instanceof Job) && typeof value.prototype?.handle !== "function")
|
|
685
483
|
throw new TypeError(`Invalid job at ${location}: expected a class with nonempty static jobName and handle().`);
|
|
686
484
|
}
|
|
687
|
-
async function
|
|
485
|
+
async function load(registry, options, current) {
|
|
688
486
|
const jobs = new Map;
|
|
689
487
|
const add = (name, identity, create, location) => {
|
|
690
488
|
const previous = jobs.get(name);
|
|
@@ -706,7 +504,7 @@ async function load3(options, current) {
|
|
|
706
504
|
}
|
|
707
505
|
}
|
|
708
506
|
} else {
|
|
709
|
-
for (const file of await infrastructureFiles(options.directory ??
|
|
507
|
+
for (const file of await infrastructureFiles(options.directory ?? join2(process.cwd(), "src", "jobs"), options.exclude)) {
|
|
710
508
|
const exports = await importInfrastructure(file);
|
|
711
509
|
const defaultValue = exports.default;
|
|
712
510
|
const legacy = defaultValue && typeof defaultValue === "object" && "default" in defaultValue ? defaultValue.default : defaultValue;
|
|
@@ -729,31 +527,31 @@ async function load3(options, current) {
|
|
|
729
527
|
}
|
|
730
528
|
if (!current())
|
|
731
529
|
return [...jobs.keys()];
|
|
732
|
-
const registered =
|
|
530
|
+
const registered = state(registry).registered;
|
|
733
531
|
for (const [name, entry] of jobs) {
|
|
734
532
|
const previous = registered.get(name);
|
|
735
533
|
if (previous && previous.identity !== entry.identity)
|
|
736
534
|
throw new Error(`Duplicate discovered job "${name}" at ${entry.location}; first declared at ${previous.location}.`);
|
|
737
535
|
}
|
|
738
|
-
const existing = new Set(
|
|
536
|
+
const existing = new Set(registry.names());
|
|
739
537
|
for (const [name, entry] of jobs) {
|
|
740
538
|
if (!existing.has(name)) {
|
|
741
|
-
|
|
539
|
+
registry.register(name, entry.create);
|
|
742
540
|
registered.set(name, entry);
|
|
743
541
|
}
|
|
744
542
|
}
|
|
745
543
|
return [...jobs.keys()];
|
|
746
544
|
}
|
|
747
|
-
function discoverJobs(options = {}) {
|
|
748
|
-
const cache =
|
|
545
|
+
function discoverJobs(registry, options = {}) {
|
|
546
|
+
const cache = state(registry).loads;
|
|
749
547
|
const key = options.manifest ?? JSON.stringify([
|
|
750
|
-
|
|
548
|
+
resolve(options.directory ?? join2(process.cwd(), "src", "jobs")),
|
|
751
549
|
[...options.exclude ?? []].sort()
|
|
752
550
|
]);
|
|
753
551
|
const existing = cache.get(key);
|
|
754
552
|
if (existing)
|
|
755
553
|
return existing;
|
|
756
|
-
const pending =
|
|
554
|
+
const pending = load(registry, options, () => state(registry).loads === cache).catch((error) => {
|
|
757
555
|
if (cache.get(key) === pending)
|
|
758
556
|
cache.delete(key);
|
|
759
557
|
throw error;
|
|
@@ -761,138 +559,171 @@ function discoverJobs(options = {}) {
|
|
|
761
559
|
cache.set(key, pending);
|
|
762
560
|
return pending;
|
|
763
561
|
}
|
|
764
|
-
function resetDiscoverJobsForTests() {
|
|
765
|
-
|
|
766
|
-
|
|
562
|
+
function resetDiscoverJobsForTests(registry) {
|
|
563
|
+
state(registry).loads = new Map;
|
|
564
|
+
state(registry).registered = new Map;
|
|
767
565
|
}
|
|
768
566
|
|
|
769
567
|
// ../../src/bootstrap/queue/defaultJobs.ts
|
|
770
568
|
import { ExportAuditLogsJob } from "@getstrata/core/jobs/exportAuditLogsJob";
|
|
771
|
-
import { InvalidateCacheTagsJob
|
|
772
|
-
|
|
773
|
-
|
|
774
|
-
|
|
775
|
-
|
|
776
|
-
|
|
569
|
+
import { InvalidateCacheTagsJob } from "@getstrata/core/jobs/invalidateCacheTagsJob";
|
|
570
|
+
var SYSTEM_JOB_NAMES = Object.freeze([
|
|
571
|
+
InvalidateCacheTagsJob.jobName,
|
|
572
|
+
ExportAuditLogsJob.jobName
|
|
573
|
+
]);
|
|
574
|
+
function registerDefaultJobs(registry) {
|
|
575
|
+
registry.register(InvalidateCacheTagsJob.jobName, () => {
|
|
576
|
+
return new InvalidateCacheTagsJob;
|
|
777
577
|
});
|
|
778
|
-
|
|
578
|
+
registry.register(ExportAuditLogsJob.jobName, () => new ExportAuditLogsJob);
|
|
779
579
|
}
|
|
780
580
|
|
|
781
581
|
// ../../src/bootstrap/providers/queue.ts
|
|
782
|
-
|
|
783
|
-
|
|
784
|
-
|
|
785
|
-
|
|
786
|
-
|
|
787
|
-
|
|
788
|
-
|
|
789
|
-
|
|
790
|
-
|
|
791
|
-
|
|
792
|
-
|
|
793
|
-
|
|
794
|
-
|
|
795
|
-
|
|
796
|
-
}
|
|
797
|
-
|
|
582
|
+
function createQueueProvider(env = process.env, handoff) {
|
|
583
|
+
const environment = Object.freeze({ ...env });
|
|
584
|
+
const retryPolicy = resolveQueueConfig2(environment);
|
|
585
|
+
const runtime = resolveQueueRuntimeConfig(environment);
|
|
586
|
+
return {
|
|
587
|
+
name: "core.queue",
|
|
588
|
+
async register({ container, config, onCleanup, invoke }) {
|
|
589
|
+
const configuredDriver = environment.QUEUE_DRIVER ?? DEFAULT_QUEUE_DRIVER;
|
|
590
|
+
const driver = configuredDriver === "async" || configuredDriver === "redis" || configuredDriver === "sync" ? configuredDriver : DEFAULT_QUEUE_DRIVER;
|
|
591
|
+
config.set("queue.driver", driver);
|
|
592
|
+
const failedJobs = createSystemQueueServices(invoke, {
|
|
593
|
+
cache: container.resolve(CORE_CACHE_TOKEN),
|
|
594
|
+
auditExport: createAuditExporter({
|
|
595
|
+
environment,
|
|
596
|
+
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))
|
|
597
|
+
})
|
|
598
|
+
}, handoff, SYSTEM_JOB_NAMES);
|
|
599
|
+
container.set(FAILED_JOB_SERVICE_TOKEN, failedJobs);
|
|
600
|
+
const registry = new JobRegistry;
|
|
601
|
+
registerDefaultJobs(registry);
|
|
602
|
+
await discoverJobs(registry);
|
|
603
|
+
const queue = createAppQueue(driver, config.get(REDIS_URL_CONFIG_KEY) ?? environment.REDIS_URL, failedJobs, registry, retryPolicy, runtime);
|
|
604
|
+
onCleanup(() => queue.close?.(), driver === "async" ? "drain" : "close");
|
|
605
|
+
container.set(CORE_QUEUE_TOKEN, queue);
|
|
606
|
+
container.set(QUEUE_JOB_REGISTRY_TOKEN, registry);
|
|
607
|
+
}
|
|
608
|
+
};
|
|
609
|
+
}
|
|
798
610
|
|
|
799
611
|
// ../../src/bootstrap/providers/storage.ts
|
|
800
|
-
import {
|
|
801
|
-
|
|
802
|
-
|
|
803
|
-
|
|
804
|
-
|
|
805
|
-
|
|
806
|
-
};
|
|
807
|
-
|
|
612
|
+
import { service } from "@getstrata/core/contracts/services";
|
|
613
|
+
import {
|
|
614
|
+
CORE_STORAGE_TOKEN,
|
|
615
|
+
createStorageDriver,
|
|
616
|
+
StorageManager,
|
|
617
|
+
snapshotStorageConfig
|
|
618
|
+
} from "@getstrata/core/storage/storage";
|
|
619
|
+
function assertStorageDriver(driver) {
|
|
620
|
+
if (!driver || [driver.put, driver.get, driver.delete].some((method) => typeof method !== "function"))
|
|
621
|
+
throw new TypeError("Storage requires put, get, and delete capabilities.");
|
|
622
|
+
}
|
|
623
|
+
function createStorageProvider(driver) {
|
|
624
|
+
assertStorageDriver(driver);
|
|
625
|
+
return Object.freeze({
|
|
626
|
+
name: "core.storage",
|
|
627
|
+
register({ dependencies }) {
|
|
628
|
+
dependencies.storage = new StorageManager(driver);
|
|
629
|
+
}
|
|
630
|
+
});
|
|
631
|
+
}
|
|
808
632
|
|
|
809
633
|
// ../../src/bootstrap/providers/tracing.ts
|
|
810
|
-
import {
|
|
811
|
-
|
|
812
|
-
|
|
813
|
-
|
|
814
|
-
|
|
815
|
-
|
|
816
|
-
|
|
817
|
-
|
|
818
|
-
|
|
819
|
-
|
|
634
|
+
import { CORE_TRACING_RUNTIME_TOKEN } from "@getstrata/core/contracts/serviceTokens";
|
|
635
|
+
import {
|
|
636
|
+
captureTracingOptions,
|
|
637
|
+
createTracingRuntime
|
|
638
|
+
} from "@getstrata/core/tracing/tracingMiddleware";
|
|
639
|
+
function createTracingProvider(options = {}) {
|
|
640
|
+
const configured = captureTracingOptions(options);
|
|
641
|
+
let registered = false;
|
|
642
|
+
return {
|
|
643
|
+
name: "core.tracing",
|
|
644
|
+
register({ container, onCleanup }) {
|
|
645
|
+
if (registered)
|
|
646
|
+
throw new Error("A tracing provider belongs to one application context; create a new provider for each context.");
|
|
647
|
+
registered = true;
|
|
648
|
+
const runtime = createTracingRuntime(configured);
|
|
649
|
+
onCleanup(() => runtime.shutdown(), "close");
|
|
650
|
+
onCleanup(() => runtime.forceFlush(), "flush");
|
|
651
|
+
container.set(CORE_TRACING_RUNTIME_TOKEN, runtime);
|
|
652
|
+
}
|
|
653
|
+
};
|
|
654
|
+
}
|
|
820
655
|
|
|
821
656
|
// ../../src/bootstrap/providers/view.ts
|
|
822
|
-
import {
|
|
823
|
-
import {
|
|
824
|
-
import {
|
|
657
|
+
import { resolve as resolve2 } from "path";
|
|
658
|
+
import { csrfTokenOptionsFromEnvironment } from "@getstrata/core/http/csrfToken";
|
|
659
|
+
import { flashSessionOptionsFromEnvironment } from "@getstrata/core/http/flashSession";
|
|
660
|
+
import { isViewsMode, parseFrontendMode as parseFrontendMode2 } from "@getstrata/core/runtime/frontendMode";
|
|
825
661
|
import {
|
|
826
|
-
|
|
827
|
-
configureWebErrorView,
|
|
828
|
-
configureWebLayoutData,
|
|
662
|
+
createWebErrorView,
|
|
829
663
|
createWebLayoutDataResolver,
|
|
830
|
-
DEFAULT_VIEWS_DIRECTORY,
|
|
831
664
|
EtaViewEngine,
|
|
832
665
|
errorTemplateName,
|
|
833
|
-
resolveWebLayoutData,
|
|
834
666
|
ViewRenderer
|
|
835
667
|
} from "@getstrata/core/view";
|
|
836
|
-
|
|
668
|
+
import {
|
|
669
|
+
CORE_VIEW_RENDERER_TOKEN,
|
|
670
|
+
CORE_VIEW_TOKEN,
|
|
671
|
+
CORE_WEB_ERROR_VIEW_TOKEN
|
|
672
|
+
} from "@getstrata/core/view/tokens";
|
|
837
673
|
var VIEW_DIRECTORY_CONFIG_KEY = "view.directory";
|
|
838
674
|
function createViewProvider(options = {}) {
|
|
839
|
-
const
|
|
675
|
+
const env = { ...options.env ?? process.env };
|
|
676
|
+
const enabled = options.enabled ?? isViewsMode(parseFrontendMode2(env.FRONTEND_MODE));
|
|
677
|
+
const directory = resolve2(options.rootDir ?? process.cwd(), options.directory ?? (env.VIEW_DIRECTORY?.trim() || "resources/views"));
|
|
840
678
|
const layout = options.layout;
|
|
841
|
-
const
|
|
679
|
+
const appName = env.APP_NAME?.trim() || "Strata";
|
|
680
|
+
const extra = options.data?.extra;
|
|
681
|
+
const defaults = { appName, currentOrganization: null, organizations: [] };
|
|
682
|
+
const data = {
|
|
683
|
+
...options.data,
|
|
684
|
+
csrf: options.data?.csrf ? { ...options.data.csrf } : enabled ? csrfTokenOptionsFromEnvironment(env) : undefined,
|
|
685
|
+
flash: options.data?.flash ? { ...options.data.flash } : enabled ? flashSessionOptionsFromEnvironment(env) : undefined,
|
|
686
|
+
extra: typeof extra === "function" ? async (user) => ({ ...defaults, ...await extra(user) }) : { ...defaults, ...extra }
|
|
687
|
+
};
|
|
688
|
+
const customErrorRender = options.error?.render;
|
|
842
689
|
return {
|
|
843
690
|
name: "view",
|
|
844
691
|
register({ container, config }) {
|
|
845
|
-
if (!
|
|
692
|
+
if (!enabled)
|
|
846
693
|
return;
|
|
847
|
-
|
|
848
|
-
|
|
849
|
-
const engine = new EtaViewEngine(viewsDirectory, createWebLayoutDataResolver(container, data));
|
|
694
|
+
config.set(VIEW_DIRECTORY_CONFIG_KEY, directory);
|
|
695
|
+
const engine = new EtaViewEngine(directory, createWebLayoutDataResolver(container, data));
|
|
850
696
|
container.set(CORE_VIEW_TOKEN, engine);
|
|
851
697
|
container.set(CORE_VIEW_RENDERER_TOKEN, new ViewRenderer(engine, layout));
|
|
698
|
+
container.set(CORE_WEB_ERROR_VIEW_TOKEN, createWebErrorView({
|
|
699
|
+
render: customErrorRender ?? ((input) => engine.render(errorTemplateName(input.status), {
|
|
700
|
+
title: input.title,
|
|
701
|
+
message: input.message,
|
|
702
|
+
errors: input.errors
|
|
703
|
+
}, { layout, request: input.request }))
|
|
704
|
+
}));
|
|
852
705
|
}
|
|
853
706
|
};
|
|
854
707
|
}
|
|
855
|
-
var viewProvider = {
|
|
856
|
-
name: "view",
|
|
857
|
-
register({ container, config }) {
|
|
858
|
-
if (!isViewsEnabled()) {
|
|
859
|
-
return;
|
|
860
|
-
}
|
|
861
|
-
const viewsDirectory = process.env.VIEW_DIRECTORY?.trim() || DEFAULT_VIEWS_DIRECTORY;
|
|
862
|
-
config.set(VIEW_DIRECTORY_CONFIG_KEY, viewsDirectory);
|
|
863
|
-
const engine = new EtaViewEngine(viewsDirectory, (request) => resolveWebLayoutData(container, request ?? currentRequestMeta().request));
|
|
864
|
-
container.set(CORE_VIEW_TOKEN, engine);
|
|
865
|
-
container.set(CORE_VIEW_RENDERER_TOKEN, new ViewRenderer(engine));
|
|
866
|
-
configureWebLayoutData({
|
|
867
|
-
extra: async () => ({
|
|
868
|
-
appName: appDisplayName(),
|
|
869
|
-
currentOrganization: null,
|
|
870
|
-
organizations: []
|
|
871
|
-
})
|
|
872
|
-
});
|
|
873
|
-
configureWebErrorView({
|
|
874
|
-
render: async (input) => engine.render(errorTemplateName(input.status), {
|
|
875
|
-
title: input.title,
|
|
876
|
-
message: input.message,
|
|
877
|
-
errors: input.errors
|
|
878
|
-
})
|
|
879
|
-
});
|
|
880
|
-
}
|
|
881
|
-
};
|
|
882
708
|
|
|
883
709
|
// ../../src/bootstrap/providers/index.ts
|
|
884
|
-
|
|
885
|
-
|
|
886
|
-
|
|
887
|
-
|
|
888
|
-
|
|
889
|
-
|
|
890
|
-
|
|
891
|
-
|
|
892
|
-
|
|
893
|
-
|
|
894
|
-
|
|
895
|
-
|
|
710
|
+
function createCoreProviders(env = process.env) {
|
|
711
|
+
env = Object.freeze({ ...env });
|
|
712
|
+
const configProvider = createConfigProvider(env);
|
|
713
|
+
const cacheProvider = createCacheProvider(env);
|
|
714
|
+
const storageProvider = createStorageProvider(createStorageDriver2(resolveStorageConfig(env)));
|
|
715
|
+
return [
|
|
716
|
+
configProvider,
|
|
717
|
+
createTracingProvider({ env }),
|
|
718
|
+
cacheProvider,
|
|
719
|
+
storageProvider,
|
|
720
|
+
auth_default,
|
|
721
|
+
policy_default,
|
|
722
|
+
createQueueProvider(env),
|
|
723
|
+
createViewProvider({ env })
|
|
724
|
+
];
|
|
725
|
+
}
|
|
896
726
|
export {
|
|
897
|
-
|
|
727
|
+
createCoreProviders,
|
|
728
|
+
resolveHttpResponsePolicy
|
|
898
729
|
};
|