create-strata 3.1.1 → 3.1.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.
package/README.md
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# create-strata
|
|
2
2
|
|
|
3
|
-
Create a [Strata](https://github.com/EyK-26/strata/blob/main/README.md)
|
|
3
|
+
Create a Laravel-inspired Bun and TypeScript application with [Strata](https://github.com/EyK-26/strata/blob/main/README.md). Requires Bun >=1.4.4; tested on Bun 1.4.4.
|
|
4
4
|
|
|
5
5
|
```bash
|
|
6
6
|
bunx create-strata my-app
|
|
@@ -38,7 +38,7 @@ bun run dev
|
|
|
38
38
|
|
|
39
39
|
Other choices may need database services or a frontend build; follow the generated README. Apps use model classes in `src/models`, named actions in `src/http/controllers`, and route declarations in `src/routes/web.ts` and `src/routes/api.ts`.
|
|
40
40
|
|
|
41
|
-
The
|
|
41
|
+
The generated package.json includes the application-local `strata` CLI; `bun install` installs it. Run the generated `bun run` scripts or `bunx strata <command>` from inside the app directory.
|
|
42
42
|
|
|
43
43
|
`create-strata` and [`@getstrata/starter`](https://www.npmjs.com/package/@getstrata/starter) provide the same generator.
|
|
44
44
|
|
package/dist/cli.js
CHANGED
|
@@ -394,12 +394,11 @@ function compileStarterFeatures(input, reference) {
|
|
|
394
394
|
"src/routes/api.ts",
|
|
395
395
|
"src/routes/web.ts",
|
|
396
396
|
"src/routes/index.ts",
|
|
397
|
-
"src/models/Note.ts",
|
|
398
397
|
"src/models/register.ts",
|
|
399
398
|
"src/db/migrations/0001_starter_schema.ts"
|
|
400
399
|
];
|
|
401
400
|
if (decisions.users)
|
|
402
|
-
artifacts.push("src/http/controllers/AuthController.ts", "src/http/auth/account.ts", "src/models/User.ts", "src/models/AuthOneTimeToken.ts", "src/db/migrations/0006_account_state.ts");
|
|
401
|
+
artifacts.push("src/http/controllers/AuthController.ts", "src/http/auth/account.ts", "src/models/User.ts", "src/db/factories/UserFactory.ts", "src/models/AuthOneTimeToken.ts", "src/db/migrations/0006_account_state.ts");
|
|
403
402
|
if (decisions.cookie)
|
|
404
403
|
artifacts.push("src/http/controllers/AuthWebController.ts");
|
|
405
404
|
if (decisions.serverViews)
|
|
@@ -419,7 +418,7 @@ function compileStarterFeatures(input, reference) {
|
|
|
419
418
|
if (layers.extras.billing)
|
|
420
419
|
artifacts.push("src/billing/applyStripeWebhook.ts", "src/http/controllers/BillingController.ts");
|
|
421
420
|
if (layers.extras.webhooks)
|
|
422
|
-
artifacts.push("src/jobs/dispatchOutboundWebhookJob.ts", "src/
|
|
421
|
+
artifacts.push("src/jobs/dispatchOutboundWebhookJob.ts", "src/webhooks/dispatchWebhook.ts");
|
|
423
422
|
if (decisions.workTracker)
|
|
424
423
|
artifacts.push("docs/WORK_TRACKER.md", "src/domain/workTracker.ts", "src/models/workTracker.ts", "src/http/controllers/WorkTrackerController.ts", "src/http/requests/WorkRequest.ts", "src/db/migrations/0007_work_tracker.ts");
|
|
425
424
|
return Object.freeze({
|
|
@@ -1172,7 +1171,7 @@ var EXTRA_CHOICES = [
|
|
|
1172
1171
|
{ value: "oauthGithub", label: "oauth-github: GitHub cookie login at /auth/github" },
|
|
1173
1172
|
{ value: "oidc", label: "oidc: OIDC cookie login at /auth/oidc (PKCE cookie)" },
|
|
1174
1173
|
{ value: "billing", label: "billing: Stripe webhook stub + GET /api/v1/billing/subscription" },
|
|
1175
|
-
{ value: "webhooks", label: "webhooks: outbound
|
|
1174
|
+
{ value: "webhooks", label: "webhooks: outbound event delivery (webhook.dispatch)" }
|
|
1176
1175
|
];
|
|
1177
1176
|
function isInteractive(flags) {
|
|
1178
1177
|
if (flags.yes || flags.noInteractive) {
|
|
@@ -1429,6 +1428,8 @@ Selected extras: ${extras.join(", ") || "none"}.
|
|
|
1429
1428
|
- src/policies/: resource access rules when needed.
|
|
1430
1429
|
- src/models/: model classes; add new classes to src/models/register.ts.
|
|
1431
1430
|
- src/db/migrations/: explicit schema changes, separate from model declarations.
|
|
1431
|
+
${decisions.users ? `- src/db/factories/UserFactory.ts: user test data with explicit credentials and invocation-owned persistence.
|
|
1432
|
+
` : ""}- src/db/seed.ts: explicit development-only seed entrypoint.
|
|
1432
1433
|
- src/config/app.ts and src/bootstrap/: configuration and dependency composition.
|
|
1433
1434
|
${decisions.serverViews || decisions.mfaViews ? `- views/: Eta templates; use the existing view rendering and escaping helpers.
|
|
1434
1435
|
` : ""}${decisions.frontendBuild ? `- frontend/: React UI built by Bun; preserve the configured SPA prefix (${layers.spaPrefix}).
|
|
@@ -1551,8 +1552,9 @@ class ControllerActions {
|
|
|
1551
1552
|
const indentation = Math.min(...lines.filter((line) => line.trim()).map((line) => line.match(/^\s*/)?.[0].length ?? 0));
|
|
1552
1553
|
const formatted = lines.map((line) => line.trim() ? ` ${line.slice(indentation)}` : "").join(`
|
|
1553
1554
|
`);
|
|
1554
|
-
|
|
1555
|
-
|
|
1555
|
+
const usedScope = scope.filter((binding) => new RegExp(`\\b${binding}\\b`).test(handler));
|
|
1556
|
+
return ` ${name}: BusinessRouteHandler = ${signature} => {${usedScope.length ? `
|
|
1557
|
+
const { ${usedScope.join(", ")} } = this;` : ""}
|
|
1556
1558
|
${formatted}
|
|
1557
1559
|
};`;
|
|
1558
1560
|
});
|
|
@@ -1939,7 +1941,7 @@ ${renderMfaChallengeRoutes(actions)}
|
|
|
1939
1941
|
}`)}),
|
|
1940
1942
|
},
|
|
1941
1943
|
"/api/v1/auth/logout": {
|
|
1942
|
-
POST: kernel.wrap("api", ${cookie ? "kernel.wrapIdentity(" : ""}${renderAction(actions, "logoutBearer", `async (request, _ports) => {
|
|
1944
|
+
POST: kernel.wrap("api", ${cookie ? "kernel.wrapIdentity(" : ""}${renderAction(actions, "logoutBearer", `async (${cookie ? "request" : "_request"}, _ports) => {
|
|
1943
1945
|
const payload = privateJsonResponse({ ok: true });
|
|
1944
1946
|
${cookie ? `const sessionAuth = authServices.session(_ports);
|
|
1945
1947
|
const { setCookie } = await sessionAuth.signOut(request);
|
|
@@ -2302,6 +2304,95 @@ function renderAuthImports({
|
|
|
2302
2304
|
return imports;
|
|
2303
2305
|
}
|
|
2304
2306
|
|
|
2307
|
+
// ../strata-starter/src/auth/renderHttpImports.ts
|
|
2308
|
+
function renderAuthHttpImports(context, target) {
|
|
2309
|
+
const { plan, cookie, mfa, verify, github, oidc, jsonAccounts, jsonCookieAccounts } = context;
|
|
2310
|
+
const apiMfa = jsonCookieAccounts && mfa;
|
|
2311
|
+
const browserMfa = plan.decisions.mfaViews;
|
|
2312
|
+
const names = new Set(["StarterAuthServices"]);
|
|
2313
|
+
const add = (...values) => {
|
|
2314
|
+
for (const value of values)
|
|
2315
|
+
names.add(value);
|
|
2316
|
+
};
|
|
2317
|
+
if (target === "account") {
|
|
2318
|
+
add("prepareAccountMail", "registerAccount", "completeAccountToken", "authenticatePasswordAccount", "withLoginAccount", "BusinessRequestPorts", "SelectedSession", "isUniqueConstraintError", "hashPassword", "AUTH_ONE_TIME_PURPOSES", "consumeOneTimeToken", "generateOneTimeToken", "hashOneTimeToken", "revokeStoredUserSessions", "persistConsumedRecoveryHash", "absoluteTemporarySignedUrl", "createStarterAuthDirectory", "withAuthIdentifier", "runWithLockedAuthUser", "StarterAuthUserRecord", "User", "AuthOneTimeToken");
|
|
2319
|
+
if (cookie)
|
|
2320
|
+
add("randomBytes", "privateJsonResponse");
|
|
2321
|
+
if (mfa)
|
|
2322
|
+
add("ConflictError", "generateRecoveryCodes", "hashRecoveryCode");
|
|
2323
|
+
} else {
|
|
2324
|
+
add("parseLoginCredentials");
|
|
2325
|
+
if (target === "web" || jsonAccounts)
|
|
2326
|
+
add("parseRegisterCredentials", "parseForgotPasswordEmail", "hashPassword", "AUTH_ONE_TIME_PURPOSES");
|
|
2327
|
+
if (target === "web") {
|
|
2328
|
+
add("parseFormBody", "flashResponse");
|
|
2329
|
+
if (mfa)
|
|
2330
|
+
add("verifyPassword", "completePasswordLogin", "createPasswordConfirmCookie", "sanitizeInternalPath", "buildOtpauthUrl", "generateTotpSecret", "verifyTotp");
|
|
2331
|
+
if (verify)
|
|
2332
|
+
add("assertValidSignature");
|
|
2333
|
+
} else {
|
|
2334
|
+
add("parseJsonBody", "privateJsonResponse", "resolveCsrfTokenForRequest");
|
|
2335
|
+
if (plan.decisions.token)
|
|
2336
|
+
add("randomBytes", "hashApiToken", "ApiToken");
|
|
2337
|
+
if (plan.decisions.jwt)
|
|
2338
|
+
add("signJwt");
|
|
2339
|
+
if (cookie)
|
|
2340
|
+
add("createSamlStateCookie", "verifySamlState", "clearSamlStateCookie");
|
|
2341
|
+
if (github)
|
|
2342
|
+
add("GitHubOAuthProvider", "createOAuthStateCookie", "clearOAuthStateCookie", "verifyOAuthState");
|
|
2343
|
+
if (oidc)
|
|
2344
|
+
add("OidcProvider", "createOAuthState", "verifySignedOAuthStateValue", "clearOidcPkceCookie", "readOidcPkceCookie", "sealOidcPkceCookie");
|
|
2345
|
+
if (browserMfa)
|
|
2346
|
+
add("parseFormBody", "completePasswordLogin");
|
|
2347
|
+
if (jsonCookieAccounts && (mfa || verify))
|
|
2348
|
+
add("ConflictError");
|
|
2349
|
+
if (apiMfa)
|
|
2350
|
+
add("verifyPassword", "createPasswordConfirmCookie", "required", "stringRule", "validateObject", "buildOtpauthUrl", "generateTotpSecret", "verifyTotp");
|
|
2351
|
+
}
|
|
2352
|
+
}
|
|
2353
|
+
const imports = renderAuthImports(context).flatMap((line) => {
|
|
2354
|
+
const match = /^(import (?:type )?\{ )(.+)( \} from .+;)$/.exec(line);
|
|
2355
|
+
if (!match)
|
|
2356
|
+
throw new Error(`Unsupported auth import declaration: ${line}`);
|
|
2357
|
+
const bindings = (match[2] ?? "").split(", ").filter((binding) => names.has(binding.split(" as ").at(-1)?.replace(/^type /, "") ?? ""));
|
|
2358
|
+
return bindings.length ? [`${match[1]}${bindings.join(", ")}${match[3]}`] : [];
|
|
2359
|
+
});
|
|
2360
|
+
if (target !== "account") {
|
|
2361
|
+
imports.push('import type { BusinessRouteHandler } from "@getstrata/bootstrap/persistenceContracts";');
|
|
2362
|
+
if (target === "web" || browserMfa)
|
|
2363
|
+
imports.push('import type { NamespacedViewRenderer } from "@getstrata/core/view";');
|
|
2364
|
+
const helpers = ["authenticatePasswordUser", "runWithLoginUser"];
|
|
2365
|
+
if (target === "web" || jsonAccounts)
|
|
2366
|
+
helpers.push("issueSignedAuthMail", "createRegistration", "completeSignedPasswordReset");
|
|
2367
|
+
if (target === "web") {
|
|
2368
|
+
helpers.push("redirectTo", "sessionUser");
|
|
2369
|
+
if (mfa)
|
|
2370
|
+
helpers.push("runWithLockedAccount", "persistAuthRecovery", "enrollMfa");
|
|
2371
|
+
if (verify)
|
|
2372
|
+
helpers.push("deferAuthEffect", "completeSignedEmailVerification");
|
|
2373
|
+
} else {
|
|
2374
|
+
if (plan.decisions.token)
|
|
2375
|
+
helpers.push("authTimestamp", "runAuthWrite");
|
|
2376
|
+
if (cookie)
|
|
2377
|
+
helpers.push("sessionUser", "completeBrowserSsoLogin");
|
|
2378
|
+
if (plan.decisions.jsonVerification)
|
|
2379
|
+
helpers.push("completeSignedEmailVerification");
|
|
2380
|
+
if (jsonAccounts && verify)
|
|
2381
|
+
helpers.push("deferAuthEffect");
|
|
2382
|
+
if (apiMfa || browserMfa || jsonCookieAccounts && verify)
|
|
2383
|
+
helpers.push("runWithLockedAccount");
|
|
2384
|
+
if (browserMfa)
|
|
2385
|
+
helpers.push("persistAuthRecovery", "redirectTo");
|
|
2386
|
+
if (apiMfa)
|
|
2387
|
+
helpers.push("enrollMfa");
|
|
2388
|
+
}
|
|
2389
|
+
imports.push(`import { ${helpers.join(", ")} } from "../auth/account.ts";`);
|
|
2390
|
+
}
|
|
2391
|
+
return `${imports.join(`
|
|
2392
|
+
`)}
|
|
2393
|
+
`;
|
|
2394
|
+
}
|
|
2395
|
+
|
|
2305
2396
|
// ../strata-starter/src/auth/renderingContext.ts
|
|
2306
2397
|
function createAuthRenderingContext(plan) {
|
|
2307
2398
|
const { cookie, github, oidc, mfa, bearerApi, jsonCookieAccounts, jsonAccounts } = plan.decisions;
|
|
@@ -2386,7 +2477,7 @@ async function issueSignedAuthMail(ports: BusinessRequestPorts, services: Starte
|
|
|
2386
2477
|
await deferAuthEffect(ports, () => services.mail.send(message));
|
|
2387
2478
|
}
|
|
2388
2479
|
|
|
2389
|
-
async function createRegistration(ports: BusinessRequestPorts, services: StarterAuthServices, credentials: { name: string; email: string; password: string }${verify ? ", verificationPath: string" : ""}) {
|
|
2480
|
+
async function createRegistration(ports: BusinessRequestPorts, ${verify ? "services" : "_services"}: StarterAuthServices, credentials: { name: string; email: string; password: string }${verify ? ", verificationPath: string" : ""}) {
|
|
2390
2481
|
const { email } = credentials;
|
|
2391
2482
|
return registerAccount(ports, email, {
|
|
2392
2483
|
write: runAuthWrite, transaction: runAuthTransaction,
|
|
@@ -2410,11 +2501,11 @@ async function consumeSignedAuthToken(ports: BusinessRequestPorts, request: Requ
|
|
|
2410
2501
|
return await runAuthWrite(ports, hashOneTimeToken(token), async (ports) => consumeOneTimeToken(ports.database, purpose, token));
|
|
2411
2502
|
}
|
|
2412
2503
|
|
|
2413
|
-
async function revokeUserSessions(ports: BusinessRequestPorts, userId: number) {
|
|
2504
|
+
${mfa ? `async function revokeUserSessions(ports: BusinessRequestPorts, userId: number) {
|
|
2414
2505
|
await runAuthWrite(ports, userId, async (ports) => {
|
|
2415
2506
|
await revokeStoredUserSessions(ports.database, userId, { incrementAuthVersion: true });
|
|
2416
2507
|
});
|
|
2417
|
-
}
|
|
2508
|
+
}` : ""}
|
|
2418
2509
|
|
|
2419
2510
|
${verify ? `
|
|
2420
2511
|
async function completeSignedEmailVerification(ports: BusinessRequestPorts, request: Request): Promise<boolean> {
|
|
@@ -2562,8 +2653,7 @@ function renderAuthHttp(plan) {
|
|
|
2562
2653
|
if (!plan.decisions.users)
|
|
2563
2654
|
return null;
|
|
2564
2655
|
const context = createAuthRenderingContext(plan);
|
|
2565
|
-
const imports =
|
|
2566
|
-
`);
|
|
2656
|
+
const imports = renderAuthHttpImports(context, "account");
|
|
2567
2657
|
const helperNames = [
|
|
2568
2658
|
"runWithLockedAccount",
|
|
2569
2659
|
"authTimestamp",
|
|
@@ -2583,14 +2673,6 @@ function renderAuthHttp(plan) {
|
|
|
2583
2673
|
${renderAuthHelpers(context)}
|
|
2584
2674
|
${renderMfaEnrollment(context.mfa)}
|
|
2585
2675
|
export { ${helperNames.join(", ")} };
|
|
2586
|
-
`;
|
|
2587
|
-
const controllerDependencies = renderAuthImports(context).filter((line) => !line.includes("AppModule") && !line.includes("CORE_VIEW_RENDERER_TOKEN") && !line.includes("wrapWebLogin")).map((line) => line.includes("STARTER_AUTH_SERVICES") ? 'import type { StarterAuthServices } from "../../bootstrap/auth.ts";' : line).join(`
|
|
2588
|
-
`);
|
|
2589
|
-
const controllerImports = `${controllerDependencies}
|
|
2590
|
-
${context.cookie ? `import type { NamespacedViewRenderer } from "@getstrata/core/view";
|
|
2591
|
-
` : ""}
|
|
2592
|
-
import type { BusinessRouteHandler } from "@getstrata/bootstrap/persistenceContracts";
|
|
2593
|
-
import { ${helperNames.join(", ")} } from "../auth/account.ts";
|
|
2594
2676
|
`;
|
|
2595
2677
|
const apiActions = new ControllerActions("AuthController");
|
|
2596
2678
|
const api = renderApiAuthRoutes(context, apiActions);
|
|
@@ -2598,12 +2680,12 @@ import { ${helperNames.join(", ")} } from "../auth/account.ts";
|
|
|
2598
2680
|
const construction = (views) => ` constructor(private readonly authServices: StarterAuthServices${views ? ", private readonly views: NamespacedViewRenderer" : ""}) {}`;
|
|
2599
2681
|
const files = {
|
|
2600
2682
|
"http/auth/account.ts": helpers,
|
|
2601
|
-
"http/controllers/AuthController.ts":
|
|
2683
|
+
"http/controllers/AuthController.ts": renderAuthHttpImports(context, "api") + apiActions.render(construction(plan.decisions.mfaViews), apiScope)
|
|
2602
2684
|
};
|
|
2603
2685
|
const webActions = new ControllerActions("AuthWebController");
|
|
2604
2686
|
const web = renderBrowserAuthRoutes(context, webActions);
|
|
2605
2687
|
if (web)
|
|
2606
|
-
files["http/controllers/AuthWebController.ts"] =
|
|
2688
|
+
files["http/controllers/AuthWebController.ts"] = renderAuthHttpImports(context, "web") + webActions.render(construction(true), ["authServices", "views"]);
|
|
2607
2689
|
return {
|
|
2608
2690
|
files,
|
|
2609
2691
|
api: { name: "authApiRoutes", source: api },
|
|
@@ -3206,7 +3288,6 @@ import { databaseOptions } from "./database.ts";
|
|
|
3206
3288
|
import { createStarterAuthServices, STARTER_AUTH_SERVICES } from "./auth.ts";
|
|
3207
3289
|
import { modelDefinitions${plan.decisions.workTracker ? ", repositoryDefinitions" : ""} } from "../models/register.ts";
|
|
3208
3290
|
import { applicationRoutes } from "../routes/index.ts";
|
|
3209
|
-
import { Note } from "../models/Note.ts";
|
|
3210
3291
|
import { migrate } from "../db/migrate.ts";
|
|
3211
3292
|
import { listeners } from "../outbox/registry.ts";
|
|
3212
3293
|
${plan.decisions.ensureDatabase ? `import { ensureAppDatabase } from "./ensureDatabase.ts";
|
|
@@ -3224,7 +3305,10 @@ const { bootstrapApp, createApp, createAppServer } = defineApp({
|
|
|
3224
3305
|
migrate,${plan.decisions.ensureDatabase ? `
|
|
3225
3306
|
ensureDatabase: ensureAppDatabase,` : ""}
|
|
3226
3307
|
outbox: { listeners${plan.decisions.workTracker ? ", token: WORK_TRACKER_OUTBOX" : ""} },
|
|
3227
|
-
health: async database => {
|
|
3308
|
+
health: async database => {
|
|
3309
|
+
const applied = await database.execute({ text: "SELECT name FROM framework_migrations WHERE name = '0001_starter_schema'", params: [] });
|
|
3310
|
+
return applied.length === 1;
|
|
3311
|
+
},
|
|
3228
3312
|
});
|
|
3229
3313
|
export { bootstrapApp, createApp, createAppServer };
|
|
3230
3314
|
export type { BootstrappedApp, BootstrapOptions };
|
|
@@ -3526,7 +3610,7 @@ function renderSupportingToolsReadme(projectName, plan) {
|
|
|
3526
3610
|
function renderApiDocs(projectName, plan) {
|
|
3527
3611
|
const layers = plan.layers;
|
|
3528
3612
|
const rows = ["| Method | Path | Notes |", "| --- | --- | --- |"];
|
|
3529
|
-
rows.push("| `GET` | `/health` | Plain text `ok` (200) when configured database/Redis checks succeed and
|
|
3613
|
+
rows.push("| `GET` | `/health` | Plain text `ok` (200) when configured database/Redis checks succeed and the starter schema migration is recorded in `framework_migrations`. This infrastructure probe runs outside API auth/tenancy admission, never selects a tenant or bypasses RLS, and returns no rows. `degraded` (503) when a dependency or schema check fails. Docker HEALTHCHECK uses this path. |", '| `GET` | `/ready` | JSON from the framework: `{"status":"ready","checks":{"database":"ok","redis":"skipped"}}` (200) or `not_ready` (503). `redis` is `ok` or `error` when `REDIS_URL` is set and `skipped` otherwise. It does not check the schema, so use `/health` as the deploy gate. |');
|
|
3530
3614
|
if (plan.decisions.token) {
|
|
3531
3615
|
rows.push("| `POST` | `/api/v1/auth/login` | `{ email, password }` returns `{ token }`. Requires `GET /api/v1/auth/csrf` then `X-CSRF-Token`. |", "| `GET` | `/api/v1/auth/me` | Requires `Authorization: Bearer <token>`. |");
|
|
3532
3616
|
}
|
|
@@ -3575,7 +3659,7 @@ function renderApiDocs(projectName, plan) {
|
|
|
3575
3659
|
${rows.join(`
|
|
3576
3660
|
`)}
|
|
3577
3661
|
|
|
3578
|
-
|
|
3662
|
+
Add application resources with the CLI commands below. The starter contains only the models required by your selected features.
|
|
3579
3663
|
|
|
3580
3664
|
## Auth
|
|
3581
3665
|
|
|
@@ -3585,26 +3669,14 @@ ${authNote}
|
|
|
3585
3669
|
|
|
3586
3670
|
Put HTTP actions in \`src/http/controllers/\` and register their paths and middleware in \`src/routes/api.ts\` or \`src/routes/web.ts\`. The bootstrap loads these route files once. Controller methods receive Bun's native \`Request\` and explicit request ports.
|
|
3587
3671
|
|
|
3588
|
-
\`\`\`
|
|
3589
|
-
|
|
3590
|
-
|
|
3591
|
-
|
|
3592
|
-
|
|
3593
|
-
export class NoteController {
|
|
3594
|
-
index: BusinessRouteHandler = async (_request, { database }) => {
|
|
3595
|
-
const notes = await database.model(Note).query().orderBy({ id: "desc" }).get();
|
|
3596
|
-
return Response.json({ data: notes.map(note => note.toJSON()) });
|
|
3597
|
-
};
|
|
3598
|
-
}
|
|
3599
|
-
\`\`\`
|
|
3600
|
-
|
|
3601
|
-
In \`src/routes/api.ts\`, import \`NoteController\` from \`../http/controllers/NoteController.ts\`, construct it in \`apiRoutes(context)\`, and add this map to that function's \`composeRouteMaps(...)\` arguments:
|
|
3602
|
-
|
|
3603
|
-
\`\`\`typescript
|
|
3604
|
-
{ "/api/v1/notes": { GET: context.kernel.wrapApi(notes.index) } }
|
|
3672
|
+
\`\`\`sh
|
|
3673
|
+
bun run strata make:model Product
|
|
3674
|
+
bun run strata make:controller ProductController
|
|
3675
|
+
bun run strata make:request StoreProductRequest
|
|
3676
|
+
bun run strata make:migration create_products
|
|
3605
3677
|
\`\`\`
|
|
3606
3678
|
|
|
3607
|
-
|
|
3679
|
+
Add model fields and fillable attributes, register the model in \`src/models/register.ts\`, and define its table in the migration. Register controller actions through \`context.kernel.wrapApi(...)\` in the API route map. This preserves authentication and the selected tenant policy. Use the handler's \`database\` port to bind your model to the current request. Account credential validation and workflows are provided by the framework.
|
|
3608
3680
|
|
|
3609
3681
|
Optional modules in \`src/modules/\` remain available for feature composition. They use the same kernel and execution ports.
|
|
3610
3682
|
|
|
@@ -3621,14 +3693,14 @@ function renderIntegrationsReadme(plan) {
|
|
|
3621
3693
|
layers.extras.oauthGithub ? "GitHub OAuth cookie login (`/auth/github`)" : null,
|
|
3622
3694
|
layers.extras.oidc ? "OIDC cookie login (`/auth/oidc`, PKCE in `oidc_pkce`)" : null,
|
|
3623
3695
|
layers.extras.billing ? "Stripe billing stub (`POST /billing/webhooks/stripe`, `GET /api/v1/billing/subscription`)" : null,
|
|
3624
|
-
layers.extras.webhooks ? "Outbound webhooks (
|
|
3696
|
+
layers.extras.webhooks ? "Outbound webhooks (explicit event dispatcher + `webhook.dispatch` job)" : null
|
|
3625
3697
|
].filter((row) => row !== null);
|
|
3626
3698
|
const lines = [
|
|
3627
3699
|
"## Integrations",
|
|
3628
3700
|
"",
|
|
3629
3701
|
"OAuth, billing, outbound webhooks, SIEM, and SAML are **off by default**. Commented placeholders live in `.env.example`. Framework map: [INTEGRATIONS.md](https://github.com/EyK-26/strata/blob/main/docs/INTEGRATIONS.md).",
|
|
3630
3702
|
"",
|
|
3631
|
-
"Wizard flags (any stack unless noted): `--oauth-github` and `--oidc` (cookie HTML), `--billing`, `--webhooks`. They emit controllers, routes, migrations, jobs, or listeners.
|
|
3703
|
+
"Wizard flags (any stack unless noted): `--oauth-github` and `--oidc` (cookie HTML), `--billing`, `--webhooks`. They emit controllers, routes, migrations, jobs, or listeners. Startup discovers the application\u2019s declared listeners and jobs.",
|
|
3632
3704
|
""
|
|
3633
3705
|
];
|
|
3634
3706
|
if (enabled.length > 0) {
|
|
@@ -3636,6 +3708,8 @@ function renderIntegrationsReadme(plan) {
|
|
|
3636
3708
|
} else {
|
|
3637
3709
|
lines.push("This app did not pass those flags. Turn a flag on and re-run `create-strata`, or copy the commented env block and add the integration controller and routes yourself.", "");
|
|
3638
3710
|
}
|
|
3711
|
+
if (layers.extras.webhooks)
|
|
3712
|
+
lines.push("Call `dispatchWebhook({ database, queue, options }, event, data)` from `src/webhooks/dispatchWebhook.ts` after your domain transaction commits. Supply an explicit public payload; never send account credentials. Compose the queue and options using `APPLICATION_QUEUE` and `APPLICATION_WEBHOOKS`. The dispatcher delivers to active subscriptions matching the event name or `*`; use a commit-aware model listener or outbox handler for transactional changes.", "");
|
|
3639
3713
|
return `${lines.join(`
|
|
3640
3714
|
`)}
|
|
3641
3715
|
`;
|
|
@@ -3833,7 +3907,7 @@ The image sets \`APP_ENV=production\` and \`AUTH_DEV_HEADERS=false\`; everything
|
|
|
3833
3907
|
${plan.decisions.dedicatedSigningSecret ? "- Set `SIGNED_URL_SECRET` to 32+ characters.\n" : ""}${plan.decisions.cookie ? "- Set `SESSION_SECRET` to 32+ characters.\n" : ""}${plan.decisions.token ? "- Set `TOKEN_HASH_PEPPER`.\n" : ""}${layers.extras.scim ? "- Set `SCIM_BEARER_TOKEN`.\n" : ""}${layers.extras.metrics ? "- Set `METRICS_TOKEN`.\n" : ""}${layers.extras.oauthGithub ? "- Set `OAUTH_STATE_SECRET` and `GITHUB_CLIENT_ID` / `GITHUB_CLIENT_SECRET`.\n" : ""}${layers.extras.oidc ? "- Set `OAUTH_STATE_SECRET`, `OIDC_ISSUER`, `OIDC_CLIENT_ID`, and `OIDC_CLIENT_SECRET`. Loopback issuers work outside production; set `OIDC_ALLOW_PRIVATE=true` for other private IdPs.\n" : ""}${layers.extras.billing ? "- Set `STRIPE_WEBHOOK_SECRET` when `FEATURE_BILLING=true`.\n" : ""}${plan.decisions.rls ? `- \`DATABASE_URL\` must be a \`NOBYPASSRLS\` role, not the \`postgres\` superuser. Generated apps create \`${GENERATED_POSTGRES_APP_ROLE}\` via \`db/ensure-postgres-app-role.sql\` (and Compose init on first empty volume). \`MIGRATION_DATABASE_URL\` and an explicit non-development \`STRATA_APP_PASSWORD\` belong only to the migrate/provisioning process. HTTP/workers connect to the existing role without admin credentials or role/password writes. Production boot rejects username \`postgres\` or \`root\`, then inspects \`pg_roles\` for \`rolsuper\` / \`rolbypassrls\`.
|
|
3834
3908
|
` : ""}
|
|
3835
3909
|
${layers.database === "mysql" ? "- Keep the MySQL runtime account limited to application reads/writes. Set `MIGRATION_DATABASE_URL` for the same database only in the administrative migration process; provisioning and migration callbacks use that connection and close it afterward. If unset, explicit migration commands require DDL privileges on the configured account.\n" : ""}
|
|
3836
|
-
\`strata start\` does not migrate when \`APP_ENV=production\`. Run \`bun run db:migrate\` as a deploy step. \`GET /health\` is 200 when
|
|
3910
|
+
\`strata start\` does not migrate when \`APP_ENV=production\`. Run \`bun run db:migrate\` as a deploy step. \`GET /health\` is 200 when the starter schema migration is recorded in \`framework_migrations\` and configured dependencies are available; it returns only \`ok\` or \`degraded\` without authentication or tenant selection, and 503 when a dependency or schema check fails. Use it for readiness, not process liveness. Redis jobs need a worker: \`bun run queue:work\` (requires \`REDIS_URL\`).
|
|
3837
3911
|
`;
|
|
3838
3912
|
}
|
|
3839
3913
|
// ../../src/core/runtime/appEnv.ts
|
|
@@ -4221,9 +4295,9 @@ function renderPackageJson(projectName, options = {}) {
|
|
|
4221
4295
|
"@getstrata/cli": "workspace:*",
|
|
4222
4296
|
"@getstrata/core": "workspace:*"
|
|
4223
4297
|
} : {
|
|
4224
|
-
"@getstrata/bootstrap": "^3.1.
|
|
4225
|
-
"@getstrata/cli": "^3.1.
|
|
4226
|
-
"@getstrata/core": "^3.1.
|
|
4298
|
+
"@getstrata/bootstrap": "^3.1.5",
|
|
4299
|
+
"@getstrata/cli": "^3.1.5",
|
|
4300
|
+
"@getstrata/core": "^3.1.5"
|
|
4227
4301
|
};
|
|
4228
4302
|
if (!options.plan || options.plan.decisions.serverViews || options.plan.decisions.mfaViews)
|
|
4229
4303
|
coreDeps.eta = "^4.6.0";
|
|
@@ -4328,7 +4402,6 @@ function starterSchemaStatements(plan) {
|
|
|
4328
4402
|
const layers = plan.layers;
|
|
4329
4403
|
const d = dialectFragments(layers.database);
|
|
4330
4404
|
const statements = [];
|
|
4331
|
-
const tenancyOn = plan.decisions.tenantTable;
|
|
4332
4405
|
const mfaOn = plan.decisions.mfa;
|
|
4333
4406
|
const payloadType = layers.database === "postgres" ? "JSONB NOT NULL" : `${d.text} NOT NULL`;
|
|
4334
4407
|
statements.push(`CREATE TABLE IF NOT EXISTS failed_job (
|
|
@@ -4346,13 +4419,6 @@ function starterSchemaStatements(plan) {
|
|
|
4346
4419
|
slug ${d.keyText} NOT NULL UNIQUE
|
|
4347
4420
|
)`);
|
|
4348
4421
|
}
|
|
4349
|
-
const notesTenantColumn = tenancyOn ? `
|
|
4350
|
-
tenant_id INTEGER NOT NULL DEFAULT 1,` : "";
|
|
4351
|
-
statements.push(`CREATE TABLE IF NOT EXISTS notes (
|
|
4352
|
-
id ${d.id},
|
|
4353
|
-
body ${d.text} NOT NULL,${notesTenantColumn}
|
|
4354
|
-
created_at ${d.timestamp}
|
|
4355
|
-
)`);
|
|
4356
4422
|
if (plan.decisions.users) {
|
|
4357
4423
|
const tenantColumn = plan.decisions.schemaTenants ? `
|
|
4358
4424
|
tenant_id INTEGER NOT NULL DEFAULT 1,` : "";
|
|
@@ -4411,7 +4477,7 @@ function starterSchemaStatements(plan) {
|
|
|
4411
4477
|
}
|
|
4412
4478
|
const rlsOn = plan.decisions.rls;
|
|
4413
4479
|
if (rlsOn) {
|
|
4414
|
-
const rlsTables = plan.decisions.users ? ["
|
|
4480
|
+
const rlsTables = plan.decisions.users ? ["users"] : [];
|
|
4415
4481
|
const userOwnedTables = [];
|
|
4416
4482
|
if (plan.decisions.users) {
|
|
4417
4483
|
userOwnedTables.push("auth_one_time_tokens");
|
|
@@ -4467,11 +4533,10 @@ export function withMigrationDatabase<T>(operation: (db: MigrationDatabase) => P
|
|
|
4467
4533
|
`;
|
|
4468
4534
|
}
|
|
4469
4535
|
function renderMigrateTs(plan) {
|
|
4470
|
-
const tenancyOn = plan.decisions.tenantTable;
|
|
4471
4536
|
const usersOn = plan.decisions.users;
|
|
4472
4537
|
const verifyOn = plan.decisions.emailVerification;
|
|
4473
4538
|
const rlsOn = plan.decisions.rls;
|
|
4474
|
-
const imports = usersOn ? `import {
|
|
4539
|
+
const imports = usersOn ? `import { createUserFactory } from "./factories/UserFactory.ts";
|
|
4475
4540
|
import { User } from "../models/User.ts";
|
|
4476
4541
|
` : "";
|
|
4477
4542
|
const tenant = plan.decisions.schemaTenants ? `
|
|
@@ -4480,9 +4545,9 @@ import { User } from "../models/User.ts";
|
|
|
4480
4545
|
const users = usersOn ? `
|
|
4481
4546
|
const users = selected.model(User);
|
|
4482
4547
|
if ((await users.query().value("id")) === null) {
|
|
4483
|
-
const
|
|
4484
|
-
await
|
|
4485
|
-
await
|
|
4548
|
+
const factory = await createUserFactory("StrataDemo!ChangeMe", ${plan.decisions.schemaTenants ? "1, " : ""}async values => (await users.create(values)).toObject());
|
|
4549
|
+
await factory.create({name:"Demo User",email:"demo@example.com",is_admin:false${verifyOn ? ",email_verified_at:selected.dialect.timestampValue(new Date())" : ""}});
|
|
4550
|
+
await factory.create({name:"Admin User",email:"admin@example.test",is_admin:true${verifyOn ? ",email_verified_at:selected.dialect.timestampValue(new Date())" : ""}});
|
|
4486
4551
|
}` : "";
|
|
4487
4552
|
const run = rlsOn ? `policy.run(database, {kind:"bypass"}, writeSeed)` : `database.transaction(writeSeed)`;
|
|
4488
4553
|
return `${imports}${ensureImport(plan)}import { createApplication } from "@getstrata/core/runtime/application";
|
|
@@ -4492,7 +4557,6 @@ import { createPersistenceInvocation } from "@getstrata/bootstrap/persistenceInv
|
|
|
4492
4557
|
import { migrateDatabase } from "@getstrata/core/database/migrations";
|
|
4493
4558
|
import { isProductionEnv } from "@getstrata/core/runtime/appEnv";
|
|
4494
4559
|
import { databaseOptions, databaseEnvironment } from "../bootstrap/database.ts";
|
|
4495
|
-
import { Note } from "../models/Note.ts";
|
|
4496
4560
|
import { loadStarterMigrations, withMigrationDatabase } from "./migrationRuntime.ts";
|
|
4497
4561
|
|
|
4498
4562
|
/** An explicit development-only command owns its own canonical Application. */
|
|
@@ -4500,14 +4564,12 @@ export async function seed(input: Readonly<Record<string, string | undefined>> =
|
|
|
4500
4564
|
const environment = databaseEnvironment(input);
|
|
4501
4565
|
if (isProductionEnv(environment)) throw new Error("Demo seeding is disabled in production and staging.");
|
|
4502
4566
|
${ensureCall(plan)} const connection = databaseOptions(environment);
|
|
4503
|
-
const application = createApplication({providers:[],services:createDatabaseBindings({default:"main",connections:{main:connection},models:[
|
|
4567
|
+
const application = createApplication({providers:[],services:createDatabaseBindings({default:"main",connections:{main:connection},models:[${usersOn ? "User" : ""}]})});
|
|
4504
4568
|
await application.start();
|
|
4505
4569
|
try {
|
|
4506
4570
|
const invoke = createPersistenceInvocation(application, "main");
|
|
4507
4571
|
await invoke({kind:"command",actor:{kind:"system",policy:"starter-demo-seed"}}, ({database${rlsOn ? ",policy" : ""}}) => {
|
|
4508
|
-
const writeSeed = async (selected: DatabaseSession | TransactionSession) => {${tenant}
|
|
4509
|
-
const notes = selected.model(Note);
|
|
4510
|
-
if ((await notes.query().value("id")) === null) await notes.create({body:"Welcome to Strata!"${tenancyOn ? ",tenant_id:1" : ""}});${users}
|
|
4572
|
+
const writeSeed = async (${usersOn || plan.decisions.schemaTenants ? "selected" : "_selected"}: DatabaseSession | TransactionSession) => {${tenant}${users}
|
|
4511
4573
|
};
|
|
4512
4574
|
return ${run};
|
|
4513
4575
|
});
|
|
@@ -4542,7 +4604,6 @@ function dropTables(plan) {
|
|
|
4542
4604
|
ordered.push("auth_one_time_tokens");
|
|
4543
4605
|
ordered.push("users");
|
|
4544
4606
|
}
|
|
4545
|
-
ordered.push("notes");
|
|
4546
4607
|
if (plan.decisions.schemaTenants) {
|
|
4547
4608
|
ordered.push("tenant");
|
|
4548
4609
|
}
|
|
@@ -4843,51 +4904,41 @@ export default DispatchOutboundWebhookJob;
|
|
|
4843
4904
|
export type { DispatchOutboundWebhookPayload };
|
|
4844
4905
|
`;
|
|
4845
4906
|
}
|
|
4846
|
-
function
|
|
4847
|
-
return `import type {
|
|
4848
|
-
import {
|
|
4849
|
-
import { createServiceToken } from "@getstrata/core/contracts/token";
|
|
4850
|
-
import { modelEffects, type AfterCommitRepositoryListener } from "@getstrata/core/database/definitions";
|
|
4851
|
-
import { APPLICATION_QUEUE as STARTER_QUEUE_TOKEN, APPLICATION_WEBHOOKS as STARTER_WEBHOOK_OPTIONS_TOKEN } from "@getstrata/bootstrap/application";
|
|
4852
|
-
import { Note, type NoteRecord } from "../models/Note.ts";
|
|
4907
|
+
function renderDispatchWebhook() {
|
|
4908
|
+
return `import type { DatabaseSession, TransactionSession } from "@getstrata/core/database/session";
|
|
4909
|
+
import type { QueueDispatcher } from "@getstrata/core/queue";
|
|
4853
4910
|
import DispatchOutboundWebhookJob from "../jobs/dispatchOutboundWebhookJob.ts";
|
|
4854
4911
|
|
|
4855
|
-
|
|
4856
|
-
|
|
4857
|
-
|
|
4858
|
-
|
|
4859
|
-
|
|
4860
|
-
|
|
4861
|
-
|
|
4862
|
-
|
|
4863
|
-
|
|
4864
|
-
|
|
4865
|
-
|
|
4866
|
-
|
|
4867
|
-
|
|
4868
|
-
|
|
4869
|
-
|
|
4870
|
-
|
|
4871
|
-
|
|
4872
|
-
|
|
4873
|
-
|
|
4874
|
-
|
|
4875
|
-
|
|
4876
|
-
|
|
4877
|
-
|
|
4878
|
-
|
|
4879
|
-
|
|
4880
|
-
|
|
4881
|
-
|
|
4882
|
-
|
|
4883
|
-
|
|
4884
|
-
|
|
4885
|
-
repositoryEffects: Object.freeze([modelEffects(Note, [
|
|
4886
|
-
{action: "created", afterCommit: noteCreated},
|
|
4887
|
-
])]),
|
|
4888
|
-
});
|
|
4889
|
-
|
|
4890
|
-
export default declarations;
|
|
4912
|
+
interface WebhookPorts {
|
|
4913
|
+
database: DatabaseSession | TransactionSession;
|
|
4914
|
+
queue: QueueDispatcher;
|
|
4915
|
+
options: Readonly<{ allowPrivate: boolean; signatureHeader: string }>;
|
|
4916
|
+
}
|
|
4917
|
+
|
|
4918
|
+
/** Call after commit; choose a public payload explicitly, excluding account credentials. */
|
|
4919
|
+
export async function dispatchWebhook({ database, queue, options }: WebhookPorts, event: string, data: unknown): Promise<void> {
|
|
4920
|
+
if (!event.trim()) throw new Error("A webhook event name is required.");
|
|
4921
|
+
const body = JSON.stringify({ event, data });
|
|
4922
|
+
const hooks = await database.execute<{
|
|
4923
|
+
id: number;
|
|
4924
|
+
url: string;
|
|
4925
|
+
secret: string;
|
|
4926
|
+
active: number | boolean;
|
|
4927
|
+
events: string;
|
|
4928
|
+
}>({ text: "SELECT id, url, secret, active, events FROM webhooks", params: [] });
|
|
4929
|
+
for (const hook of hooks) {
|
|
4930
|
+
if (!hook.active || (hook.events !== "*" && hook.events !== event)) continue;
|
|
4931
|
+
await queue.dispatch(new DispatchOutboundWebhookJob(), {
|
|
4932
|
+
webhookId: hook.id,
|
|
4933
|
+
event,
|
|
4934
|
+
url: hook.url,
|
|
4935
|
+
secret: hook.secret,
|
|
4936
|
+
body,
|
|
4937
|
+
allowPrivate: options.allowPrivate,
|
|
4938
|
+
signatureHeader: options.signatureHeader,
|
|
4939
|
+
});
|
|
4940
|
+
}
|
|
4941
|
+
}
|
|
4891
4942
|
`;
|
|
4892
4943
|
}
|
|
4893
4944
|
function renderApplyStripeWebhook() {
|
|
@@ -5786,7 +5837,7 @@ ${imports[kind].join(`
|
|
|
5786
5837
|
${routes.map((route) => route.source).join(`
|
|
5787
5838
|
`)}
|
|
5788
5839
|
/** Register ${kind === "api" ? "API" : "browser"} endpoints and their middleware here. */
|
|
5789
|
-
export function ${kind}Routes(context: ModuleRouteContext): AppRouteMap {
|
|
5840
|
+
export function ${kind}Routes(${routes.length ? "context" : "_context"}: ModuleRouteContext): AppRouteMap {
|
|
5790
5841
|
return composeRouteMaps(${routes.map((route) => `${route.name}(context)`).join(", ")});
|
|
5791
5842
|
}
|
|
5792
5843
|
`;
|
|
@@ -5914,15 +5965,6 @@ export type { ${name}Record };
|
|
|
5914
5965
|
export { ${name} };
|
|
5915
5966
|
`;
|
|
5916
5967
|
}
|
|
5917
|
-
function renderNoteModel(plan) {
|
|
5918
|
-
const tenant = plan.decisions.tenantTable;
|
|
5919
|
-
return renderModel("Note", "notes", {
|
|
5920
|
-
id: "field.number()",
|
|
5921
|
-
body: "field.string()",
|
|
5922
|
-
...tenant ? { tenant_id: "field.number()" } : {},
|
|
5923
|
-
created_at: "field.timestamp()"
|
|
5924
|
-
}, ["body", ...tenant ? ["tenant_id"] : []]);
|
|
5925
|
-
}
|
|
5926
5968
|
function renderUserModel(plan) {
|
|
5927
5969
|
const tenant = plan.decisions.schemaTenants;
|
|
5928
5970
|
const mfa = plan.layers.extras.mfa;
|
|
@@ -5955,6 +5997,36 @@ function renderUserModel(plan) {
|
|
|
5955
5997
|
"email_verified_at"
|
|
5956
5998
|
], ["password", ...mfa ? ["mfa_secret", "mfa_recovery_codes"] : []]);
|
|
5957
5999
|
}
|
|
6000
|
+
function renderUserFactory(plan) {
|
|
6001
|
+
return `import { hashPassword } from "@getstrata/core/auth/password";
|
|
6002
|
+
import { createFactory, type FactoryPersist } from "@getstrata/core/database/factory";
|
|
6003
|
+
import type { UserRecord } from "../../models/User.ts";
|
|
6004
|
+
|
|
6005
|
+
/** Explicit credentials and persistence keep test data local to its invocation. */
|
|
6006
|
+
export async function createUserFactory(password: string, ${plan.decisions.schemaTenants ? "tenantId: number, " : ""}persist?: FactoryPersist<UserRecord>) {
|
|
6007
|
+
const hashedPassword = await hashPassword(password);
|
|
6008
|
+
return createFactory<UserRecord>({
|
|
6009
|
+
definition: () => ({
|
|
6010
|
+
id: 0,
|
|
6011
|
+
name: "Test User",
|
|
6012
|
+
email: \`user-\${crypto.randomUUID()}@example.test\`,
|
|
6013
|
+
password: hashedPassword,
|
|
6014
|
+
is_admin: false,
|
|
6015
|
+
is_active: true,
|
|
6016
|
+
auth_version: 0,
|
|
6017
|
+
${plan.decisions.schemaTenants ? ` tenant_id: tenantId,
|
|
6018
|
+
` : ""}${plan.decisions.mfa ? ` mfa_secret: null,
|
|
6019
|
+
mfa_enabled: false,
|
|
6020
|
+
mfa_recovery_codes: null,
|
|
6021
|
+
` : ""} session_valid_after: null,
|
|
6022
|
+
email_verified_at: null,
|
|
6023
|
+
created_at: new Date().toISOString(),
|
|
6024
|
+
}),
|
|
6025
|
+
persist,
|
|
6026
|
+
});
|
|
6027
|
+
}
|
|
6028
|
+
`;
|
|
6029
|
+
}
|
|
5958
6030
|
function renderApiTokenModel() {
|
|
5959
6031
|
return renderModel("ApiToken", "api_tokens", {
|
|
5960
6032
|
id: "field.number()",
|
|
@@ -5978,7 +6050,7 @@ function renderAuthOneTimeTokenModel() {
|
|
|
5978
6050
|
}, ["purpose", "user_id", "token_hash", "expires_at", "consumed_at"]);
|
|
5979
6051
|
}
|
|
5980
6052
|
function renderModelsRegister(plan) {
|
|
5981
|
-
const names = [
|
|
6053
|
+
const names = [];
|
|
5982
6054
|
if (plan.decisions.users)
|
|
5983
6055
|
names.push("User", "AuthOneTimeToken");
|
|
5984
6056
|
if (plan.decisions.token)
|
|
@@ -6123,12 +6195,13 @@ export const TENANCY_ENABLED = ${decisions.tenantTable};
|
|
|
6123
6195
|
}
|
|
6124
6196
|
writeText(join2(src, "outbox/registry.ts"), renderOutboxRegistryTs(plan));
|
|
6125
6197
|
writeText(join2(src, "bootstrap/auth.ts"), renderAuthProvider(plan));
|
|
6126
|
-
writeText(join2(src, "models/Note.ts"), renderNoteModel(plan));
|
|
6127
6198
|
if (decisions.users) {
|
|
6128
6199
|
writeText(join2(src, "models/User.ts"), renderUserModel(plan));
|
|
6200
|
+
writeText(join2(src, "db/factories/UserFactory.ts"), renderUserFactory(plan));
|
|
6129
6201
|
writeText(join2(src, "models/AuthOneTimeToken.ts"), renderAuthOneTimeTokenModel());
|
|
6130
6202
|
} else {
|
|
6131
6203
|
removeIfExists(join2(src, "models/User.ts"));
|
|
6204
|
+
removeIfExists(join2(src, "db/factories/UserFactory.ts"));
|
|
6132
6205
|
removeIfExists(join2(src, "models/AuthOneTimeToken.ts"));
|
|
6133
6206
|
}
|
|
6134
6207
|
if (decisions.token) {
|
|
@@ -6177,10 +6250,10 @@ export const TENANCY_ENABLED = ${decisions.tenantTable};
|
|
|
6177
6250
|
}
|
|
6178
6251
|
if (layers.extras.webhooks) {
|
|
6179
6252
|
writeText(join2(src, "jobs/dispatchOutboundWebhookJob.ts"), renderDispatchOutboundWebhookJob(plan));
|
|
6180
|
-
writeText(join2(src, "
|
|
6253
|
+
writeText(join2(src, "webhooks/dispatchWebhook.ts"), renderDispatchWebhook());
|
|
6181
6254
|
} else {
|
|
6182
6255
|
removeIfExists(join2(src, "jobs/dispatchOutboundWebhookJob.ts"));
|
|
6183
|
-
removeIfExists(join2(src, "
|
|
6256
|
+
removeIfExists(join2(src, "webhooks/dispatchWebhook.ts"));
|
|
6184
6257
|
}
|
|
6185
6258
|
if (decisions.pendingMfa) {
|
|
6186
6259
|
writeText(join2(src, "bootstrap/pendingMfa.ts"), renderPendingMfaTs());
|
|
@@ -1,50 +1,5 @@
|
|
|
1
|
-
# API
|
|
1
|
+
# API routes
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
The generated `docs/API.md` describes the routes and authentication for your selected starter options.
|
|
4
4
|
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
- `GET /health` returns plain text `ok`, or `degraded` (503) until the database ping succeeds and the migrated `notes` table exists. Docker HEALTHCHECK uses `/health`.
|
|
8
|
-
- `GET /ready` returns JSON `{"status":"ready","checks":{"database":"ok","redis":"skipped"}}` (200) or `not_ready` (503). `redis` is `ok` or `error` when `REDIS_URL` is set and `skipped` otherwise. It does not check the schema, so `/health` is the deploy gate.
|
|
9
|
-
- `GET /` returns the welcome page.
|
|
10
|
-
- A `notes` table, with no routes on it yet.
|
|
11
|
-
|
|
12
|
-
Login endpoints depend on the auth layer you chose. Token auth adds `POST /api/v1/auth/login` and `GET /api/v1/auth/me`; JWT auth adds `POST /api/auth/token`; header auth adds none and expects `x-authenticated-user-id` for local work only.
|
|
13
|
-
|
|
14
|
-
There is no CRUD endpoint for `notes`. Adding your own routes is the first thing you do.
|
|
15
|
-
|
|
16
|
-
## Adding a route
|
|
17
|
-
|
|
18
|
-
```typescript
|
|
19
|
-
// src/modules/notes/index.ts
|
|
20
|
-
import type { AppModule } from "@getstrata/bootstrap/contracts";
|
|
21
|
-
import { jsonResponse } from "@getstrata/core/http/response";
|
|
22
|
-
import { getSql } from "../../bootstrap/database.ts";
|
|
23
|
-
|
|
24
|
-
const notesModule: AppModule = {
|
|
25
|
-
name: "notes",
|
|
26
|
-
order: 2,
|
|
27
|
-
routes({ kernel }) {
|
|
28
|
-
return {
|
|
29
|
-
"/api/v1/notes": kernel.wrap("api", async () => {
|
|
30
|
-
const rows = await getSql().unsafe<{ id: number; body: string }>(
|
|
31
|
-
"SELECT id, body FROM notes ORDER BY id DESC",
|
|
32
|
-
);
|
|
33
|
-
return jsonResponse({ data: rows });
|
|
34
|
-
}),
|
|
35
|
-
};
|
|
36
|
-
},
|
|
37
|
-
};
|
|
38
|
-
|
|
39
|
-
export default notesModule;
|
|
40
|
-
```
|
|
41
|
-
|
|
42
|
-
Import from `@getstrata/core/...` subpaths rather than the package root, so singleton state such as the database pool stays shared.
|
|
43
|
-
|
|
44
|
-
## Generating an app instead
|
|
45
|
-
|
|
46
|
-
```bash
|
|
47
|
-
bunx create-strata my-app --frontend api --yes
|
|
48
|
-
```
|
|
49
|
-
|
|
50
|
-
A generated app writes its own `docs/API.md` listing only the routes its layers actually serve.
|
|
5
|
+
Add application actions in `src/http/controllers/`, validation in `src/http/requests/`, and routes in `src/routes/api.ts`. Use `bun run strata make:controller ProductController` to begin. Register routes through the kernel to preserve authentication and tenant policies.
|
|
@@ -1,7 +1,5 @@
|
|
|
1
1
|
import { useAuth } from "../auth/AuthContext";
|
|
2
2
|
import { AUTH_CONFIG } from "../auth/config";
|
|
3
|
-
import { TENANCY_ENABLED } from "../config";
|
|
4
|
-
import { notesModuleExample } from "../examples/notes";
|
|
5
3
|
export default function HomePage() {
|
|
6
4
|
const { user } = useAuth();
|
|
7
5
|
return (
|
|
@@ -38,19 +36,6 @@ export default function HomePage() {
|
|
|
38
36
|
</tbody>
|
|
39
37
|
</table>
|
|
40
38
|
</div>
|
|
41
|
-
<h2>Starter-only example</h2>
|
|
42
|
-
<p>
|
|
43
|
-
This app has no notes API yet. Add an explicit module under <code>src/modules/</code> to
|
|
44
|
-
expose your own application resources through the ORM.
|
|
45
|
-
</p>
|
|
46
|
-
<pre className="card">
|
|
47
|
-
<code>{notesModuleExample(TENANCY_ENABLED)}</code>
|
|
48
|
-
</pre>
|
|
49
|
-
<p className="hint">
|
|
50
|
-
Then fetch it here with <code>apiFetch("/notes")</code>. The <code>notes</code> table
|
|
51
|
-
already exists after <code>bun run db:migrate</code>. Application authorization and tenant
|
|
52
|
-
scope remain required for real business data.
|
|
53
|
-
</p>
|
|
54
39
|
</section>
|
|
55
40
|
);
|
|
56
41
|
}
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "create-strata",
|
|
3
|
-
"version": "3.1.
|
|
4
|
-
"description": "Create
|
|
3
|
+
"version": "3.1.5",
|
|
4
|
+
"description": "Create Laravel-inspired applications with Bun and TypeScript.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"license": "MIT",
|
|
7
7
|
"repository": {
|
|
@@ -1,22 +0,0 @@
|
|
|
1
|
-
/** Displayed source only; business handlers execute after the developer adds this module. */
|
|
2
|
-
export function notesModuleExample(tenancy: boolean): string {
|
|
3
|
-
const scope = tenancy ? ".where({ tenant_id: ports.established.tenant.id })" : "";
|
|
4
|
-
return `// src/modules/notes/index.ts
|
|
5
|
-
import type { AppModule } from "@getstrata/bootstrap/contracts";
|
|
6
|
-
import { jsonResponse } from "@getstrata/core/http/response";
|
|
7
|
-
import { Note } from "../../models/Note.ts";
|
|
8
|
-
|
|
9
|
-
export default {
|
|
10
|
-
name: "notes",
|
|
11
|
-
routes({ kernel }) {
|
|
12
|
-
return {
|
|
13
|
-
"/api/v1/notes": {
|
|
14
|
-
GET: kernel.wrapApi(async (_request, ports) => {
|
|
15
|
-
const rows = await ports.database.model(Note).query()${scope}.orderBy({ column: "id", direction: "DESC" }).limit(100).get();
|
|
16
|
-
return jsonResponse({ data: rows.map(row => row.toObject()) });
|
|
17
|
-
}),
|
|
18
|
-
},
|
|
19
|
-
};
|
|
20
|
-
},
|
|
21
|
-
} satisfies AppModule;`;
|
|
22
|
-
}
|