@wwchen/stack 0.9.1 → 0.10.1
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 +23 -13
- package/blocks/AGENTS.md +4 -12
- package/blocks/CLAUDE.md +7 -15
- package/blocks/env.example +0 -11
- package/blocks/gitignore +1 -2
- package/dist/cli/builtin.d.ts +6 -0
- package/dist/cli/builtin.js +47 -0
- package/dist/cli/context.d.ts +6 -20
- package/dist/cli/context.js +2 -2
- package/dist/cli/host.d.ts +8 -0
- package/dist/cli/host.js +128 -0
- package/dist/cli/index.js +4 -71
- package/dist/cli/neon.d.ts +4 -4
- package/dist/cli/neon.js +19 -9
- package/dist/cli/run.js +1 -1
- package/dist/cli/sync-blocks.d.ts +9 -8
- package/dist/cli/sync-blocks.js +157 -47
- package/dist/configs/vitest.js +1 -6
- package/dist/connections/env.d.ts +8 -0
- package/dist/connections/env.js +15 -0
- package/dist/connections/index.d.ts +1 -1
- package/dist/connections/index.js +1 -1
- package/dist/connections/table.d.ts +5 -3
- package/dist/connections/table.js +3 -3
- package/dist/db/branches.d.ts +11 -0
- package/dist/db/branches.js +19 -0
- package/dist/db/doctor.d.ts +9 -0
- package/dist/db/doctor.js +120 -0
- package/dist/db/env.d.ts +14 -0
- package/dist/db/env.js +15 -0
- package/dist/db/health.d.ts +10 -0
- package/dist/db/health.js +26 -0
- package/dist/db/index.d.ts +1 -0
- package/dist/db/index.js +1 -0
- package/dist/db/target.js +2 -1
- package/dist/env/core-env.d.ts +23 -0
- package/dist/env/core-env.js +24 -0
- package/dist/env/define-env.d.ts +22 -10
- package/dist/env/define-env.js +72 -17
- package/dist/env/index.d.ts +2 -2
- package/dist/env/index.js +1 -1
- package/dist/http/client-ip.d.ts +6 -0
- package/dist/http/client-ip.js +21 -0
- package/dist/http/index.d.ts +2 -0
- package/dist/http/index.js +2 -0
- package/dist/http/safe-next.d.ts +11 -0
- package/dist/http/safe-next.js +30 -0
- package/dist/index.d.ts +2 -1
- package/dist/index.js +1 -1
- package/dist/next/api.d.ts +9 -8
- package/dist/next/api.js +10 -8
- package/dist/next/health.d.ts +5 -7
- package/dist/next/health.js +16 -17
- package/dist/stack/contracts.d.ts +152 -0
- package/dist/stack/contracts.js +42 -0
- package/dist/vercel/index.d.ts +28 -0
- package/dist/vercel/index.js +90 -0
- package/package.json +22 -4
- package/dist/cli/doctor.d.ts +0 -40
- package/dist/cli/doctor.js +0 -166
- package/dist/cli/migrate-suite.d.ts +0 -2
- package/dist/cli/migrate-suite.js +0 -491
- package/dist/cli/user-create.d.ts +0 -6
- package/dist/cli/user-create.js +0 -77
- package/dist/cli/vercel-build.d.ts +0 -4
- package/dist/cli/vercel-build.js +0 -61
- package/dist/env/stack-env.d.ts +0 -37
- package/dist/env/stack-env.js +0 -54
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
// The database's share of `stack vercel-build` and `stack doctor` (a composed hosting package's commands): the migrate build step, and the checks of the database variables, the Neon Vercel integration and the core's own secrets. The built-in package contributes them; never re-exported from `db/index.ts`, because it reaches the CLI's `migrate`.
|
|
2
|
+
//
|
|
3
|
+
// The build step, Neon's documented pattern: the build applies the migrations, so the deployment never goes live on a schema it was not built for.
|
|
4
|
+
// - Preview: migrates the one shared `preview` branch (see `stack neon reset-preview`), which lacks this PR's new migrations. Refuses if any of its database URLs turns out to be production.
|
|
5
|
+
// - Production: migrates production's database. A failed migration fails the build, so the new code never goes live on a schema it was not built for. The old deployment keeps serving while this runs, which is why every migration must be expand-then-contract.
|
|
6
|
+
// - Anything else (a local run): does nothing.
|
|
7
|
+
import { CliError } from "../cli/context.js";
|
|
8
|
+
import { migrate } from "../cli/neon.js";
|
|
9
|
+
import { SEVERITY, VERCEL_TARGET, } from "../stack/contracts.js";
|
|
10
|
+
import { previewOwnSecretsCheck } from "../vercel/index.js";
|
|
11
|
+
import { endpointOf } from "./index.js";
|
|
12
|
+
const DATABASE_URL = "DATABASE_URL";
|
|
13
|
+
const DATABASE_URL_UNPOOLED = "DATABASE_URL_UNPOOLED";
|
|
14
|
+
const PRODUCTION_DATABASE_HOST = "PRODUCTION_DATABASE_HOST";
|
|
15
|
+
/** Every variable the stack's env reads a database connection from. */
|
|
16
|
+
export const DATABASE_URL_VARIABLES = [DATABASE_URL, DATABASE_URL_UNPOOLED];
|
|
17
|
+
/** What the Neon Vercel integration writes on every variable it creates. */
|
|
18
|
+
export const NEON_INTEGRATION_COMMENT = "The Neon Postgres integration sets this environment variable automatically";
|
|
19
|
+
/** The core's secrets a preview must hold its own value of, never production's (runbook §3). */
|
|
20
|
+
const PREVIEW_OWN_SECRETS = [
|
|
21
|
+
"TOKEN_ENCRYPTION_KEY",
|
|
22
|
+
"CRON_SECRET",
|
|
23
|
+
];
|
|
24
|
+
const hostOf = (url) => {
|
|
25
|
+
try {
|
|
26
|
+
return new URL(url).hostname;
|
|
27
|
+
}
|
|
28
|
+
catch {
|
|
29
|
+
return "(unparseable URL)";
|
|
30
|
+
}
|
|
31
|
+
};
|
|
32
|
+
/**
|
|
33
|
+
* A deployment that migrates needs a database URL. drizzle.config.ts migrates through the direct (unpooled) endpoint when it is set, bypassing PgBouncer; without it, through the pooler.
|
|
34
|
+
*/
|
|
35
|
+
function requireDatabaseUrl(ctx, environment) {
|
|
36
|
+
if (!ctx.env[DATABASE_URL_UNPOOLED] && !ctx.env[DATABASE_URL]) {
|
|
37
|
+
// Not the Neon integration: its preview branches are cut from production, with its data.
|
|
38
|
+
const where = environment === "Preview"
|
|
39
|
+
? "the `preview` branch's URL from `stack neon reset-preview`, scoped to Preview"
|
|
40
|
+
: "production's URL, scoped to Production";
|
|
41
|
+
throw new CliError(`${environment} deployment with no ${DATABASE_URL}: set it in Vercel (${where}).`);
|
|
42
|
+
}
|
|
43
|
+
if (!ctx.env[DATABASE_URL_UNPOOLED]) {
|
|
44
|
+
ctx.error(`[build] ${environment}: no ${DATABASE_URL_UNPOOLED}; migrating through the pooler.`);
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
/** Migrates a Preview or Production deployment's database before `next build`; a refusal or a failed migration throws, which fails the build. */
|
|
48
|
+
export const migrateStep = {
|
|
49
|
+
name: "migrate",
|
|
50
|
+
async run(ctx) {
|
|
51
|
+
const environment = ctx.env.VERCEL_ENV;
|
|
52
|
+
if (environment !== VERCEL_TARGET.preview && environment !== VERCEL_TARGET.production)
|
|
53
|
+
return;
|
|
54
|
+
requireDatabaseUrl(ctx, environment === VERCEL_TARGET.preview ? "Preview" : "Production");
|
|
55
|
+
if (environment === VERCEL_TARGET.preview) {
|
|
56
|
+
// A backstop for a mis-scoped variable: a preview must never migrate or serve production. Every database URL is checked, not just the one migrate uses: the running preview reads DATABASE_URL, and Vercel previews run with NODE_ENV=production, so assertDevDatabase does not catch it at runtime. Pooled and direct hosts of one endpoint compare equal (endpointOf), whichever form each variable holds. Not optional: without production's host there is nothing to check against, and the host is not a secret, so it is set for every environment.
|
|
57
|
+
const productionHost = ctx.env[PRODUCTION_DATABASE_HOST] ?? "";
|
|
58
|
+
if (productionHost.trim() === "") {
|
|
59
|
+
throw new CliError(`${PRODUCTION_DATABASE_HOST} is not set on Preview, so this build cannot tell the ` +
|
|
60
|
+
"preview database from production. Set it in Vercel for all environments " +
|
|
61
|
+
"(production's direct host, not a secret); see the runbook.");
|
|
62
|
+
}
|
|
63
|
+
for (const name of DATABASE_URL_VARIABLES) {
|
|
64
|
+
const value = ctx.env[name];
|
|
65
|
+
if (value && endpointOf(value) === endpointOf(productionHost)) {
|
|
66
|
+
throw new CliError(`This preview's ${name} (${hostOf(value)}) is production (${productionHost.trim()}). ` +
|
|
67
|
+
"Refusing to migrate or build; scope it to the `preview` branch (see the runbook).");
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
ctx.log(`[build] ${environment}: migrating before the build.`);
|
|
72
|
+
// The database is remote by design; the guard's opt-in says this command means it.
|
|
73
|
+
const status = await migrate(ctx, { ...ctx.env, ALLOW_REMOTE_DATABASE: "1" });
|
|
74
|
+
if (status !== 0)
|
|
75
|
+
throw new CliError(`drizzle-kit migrate failed (exit ${status}).`);
|
|
76
|
+
},
|
|
77
|
+
};
|
|
78
|
+
/** Variables named `key` that apply to every deployment of `target`: no single git branch. */
|
|
79
|
+
const covering = (h, key, target) => h.envs.filter((v) => v.key === key && v.target.includes(target) && !v.gitBranch);
|
|
80
|
+
const fromNeonIntegration = (v) => (v.configurationId !== undefined && v.gitBranch !== undefined) ||
|
|
81
|
+
(v.comment?.includes(NEON_INTEGRATION_COMMENT) === true &&
|
|
82
|
+
v.target.includes(VERCEL_TARGET.preview));
|
|
83
|
+
/** The database's and the core's variables, on metadata alone. */
|
|
84
|
+
export async function databaseChecks(h) {
|
|
85
|
+
const findings = [];
|
|
86
|
+
const add = (severity, message) => findings.push({ severity, message });
|
|
87
|
+
const integration = h.envs.filter(fromNeonIntegration);
|
|
88
|
+
if (integration.length > 0) {
|
|
89
|
+
const names = [
|
|
90
|
+
...new Set(integration.map((v) => (v.gitBranch ? `${v.key} (${v.gitBranch})` : v.key))),
|
|
91
|
+
];
|
|
92
|
+
add(SEVERITY.error, `The Neon Vercel integration is creating per-preview database variables: ${names.join(", ")}. ` +
|
|
93
|
+
"It cuts each preview's branch from production, copying production's data into previews. " +
|
|
94
|
+
"Turn off its preview branching (Vercel, Integrations, Neon), remove these variables, and " +
|
|
95
|
+
"point Preview at the shared `preview` branch: `stack neon reset-preview --set-vercel`.");
|
|
96
|
+
}
|
|
97
|
+
findings.push(...(await previewOwnSecretsCheck(PREVIEW_OWN_SECRETS)(h)));
|
|
98
|
+
for (const target of Object.values(VERCEL_TARGET)) {
|
|
99
|
+
if (covering(h, PRODUCTION_DATABASE_HOST, target).length === 0) {
|
|
100
|
+
add(target === VERCEL_TARGET.development ? SEVERITY.warning : SEVERITY.error, `${PRODUCTION_DATABASE_HOST} is not set for ${target}: set production's direct host (not a ` +
|
|
101
|
+
"secret) in every environment, so builds and local tooling can refuse production." +
|
|
102
|
+
(target === VERCEL_TARGET.preview
|
|
103
|
+
? " `stack vercel-build` refuses a preview build without it."
|
|
104
|
+
: ""));
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
if (covering(h, DATABASE_URL_UNPOOLED, VERCEL_TARGET.production).length === 0) {
|
|
108
|
+
add(SEVERITY.warning, `${DATABASE_URL_UNPOOLED} is not set for Production, so migrations run through the pooler. ` +
|
|
109
|
+
"Set it to production's direct (non -pooler) URL.");
|
|
110
|
+
}
|
|
111
|
+
if (covering(h, DATABASE_URL, VERCEL_TARGET.preview).length === 0) {
|
|
112
|
+
add(SEVERITY.error, `Preview has no ${DATABASE_URL}, so every preview build fails. Run \`stack neon reset-preview ` +
|
|
113
|
+
"--set-vercel` to point Preview at the shared `preview` branch.");
|
|
114
|
+
}
|
|
115
|
+
else {
|
|
116
|
+
add(SEVERITY.info, `Whether Preview's ${DATABASE_URL} is production's database can only be told from its value, ` +
|
|
117
|
+
"which doctor never reads; `stack vercel-build` refuses that at build time.");
|
|
118
|
+
}
|
|
119
|
+
return findings;
|
|
120
|
+
}
|
package/dist/db/env.d.ts
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
/** The database's variables, an env fragment for `defineEnv({ fragments })`. */
|
|
3
|
+
export declare const dbEnv: {
|
|
4
|
+
readonly name: "dbEnv";
|
|
5
|
+
readonly schema: {
|
|
6
|
+
readonly DATABASE_URL: z.ZodString;
|
|
7
|
+
readonly DATABASE_URL_UNPOOLED: z.ZodOptional<z.ZodString>;
|
|
8
|
+
readonly PRODUCTION_DATABASE_HOST: z.ZodOptional<z.ZodString>;
|
|
9
|
+
};
|
|
10
|
+
readonly productionRequired: readonly ["DATABASE_URL"];
|
|
11
|
+
readonly buildPlaceholders: {
|
|
12
|
+
readonly DATABASE_URL: "postgres://unused:unused@127.0.0.1:1/unused";
|
|
13
|
+
};
|
|
14
|
+
};
|
package/dist/db/env.js
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
// Loaded by the app's `env.ts`, so it imports nothing but zod: never `pg` or the database client.
|
|
2
|
+
import { z } from "zod";
|
|
3
|
+
/** The database's variables, an env fragment for `defineEnv({ fragments })`. */
|
|
4
|
+
export const dbEnv = {
|
|
5
|
+
name: "dbEnv",
|
|
6
|
+
schema: {
|
|
7
|
+
DATABASE_URL: z.string().min(1),
|
|
8
|
+
DATABASE_URL_UNPOOLED: z.string().optional(),
|
|
9
|
+
// Production's database host, so local tooling can refuse it.
|
|
10
|
+
PRODUCTION_DATABASE_HOST: z.string().optional(),
|
|
11
|
+
},
|
|
12
|
+
productionRequired: ["DATABASE_URL"],
|
|
13
|
+
// Stands in for a connection string during a build, which never opens a connection.
|
|
14
|
+
buildPlaceholders: { DATABASE_URL: "postgres://unused:unused@127.0.0.1:1/unused" },
|
|
15
|
+
};
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import type { NodePgDatabase } from "drizzle-orm/node-postgres";
|
|
2
|
+
import type { HealthCheck } from "../stack/contracts.ts";
|
|
3
|
+
/**
|
|
4
|
+
* The database's health check, for `healthRoute({ checks: [databaseCheck(db)] })`: `{ db: "up", migrations }` when `select 1` answers, `{ db: "down", migrations: "unknown" }` when it does not. `migrations` is `migrationStatus` against `migrationsFolder`, or `"unknown"` when that read fails.
|
|
5
|
+
*
|
|
6
|
+
* `migrationsFolder` defaults to `drizzle/` under the working directory; `withStack` traces `./drizzle/**` into `/api/health` so the folder exists in a deployment.
|
|
7
|
+
*/
|
|
8
|
+
export declare function databaseCheck(db: NodePgDatabase<any>, opts?: {
|
|
9
|
+
migrationsFolder?: string;
|
|
10
|
+
}): HealthCheck;
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import path from "node:path";
|
|
2
|
+
import { sql } from "drizzle-orm";
|
|
3
|
+
import { migrationStatus } from "./migration-status.js";
|
|
4
|
+
/**
|
|
5
|
+
* The database's health check, for `healthRoute({ checks: [databaseCheck(db)] })`: `{ db: "up", migrations }` when `select 1` answers, `{ db: "down", migrations: "unknown" }` when it does not. `migrations` is `migrationStatus` against `migrationsFolder`, or `"unknown"` when that read fails.
|
|
6
|
+
*
|
|
7
|
+
* `migrationsFolder` defaults to `drizzle/` under the working directory; `withStack` traces `./drizzle/**` into `/api/health` so the folder exists in a deployment.
|
|
8
|
+
*/
|
|
9
|
+
export function databaseCheck(
|
|
10
|
+
// biome-ignore lint/suspicious/noExplicitAny: any schema
|
|
11
|
+
db, opts = {}) {
|
|
12
|
+
const migrationsFolder = opts.migrationsFolder ?? path.join(process.cwd(), "drizzle");
|
|
13
|
+
return {
|
|
14
|
+
name: "database",
|
|
15
|
+
async check() {
|
|
16
|
+
try {
|
|
17
|
+
await db.execute(sql `select 1`);
|
|
18
|
+
}
|
|
19
|
+
catch {
|
|
20
|
+
return { db: "down", migrations: "unknown" };
|
|
21
|
+
}
|
|
22
|
+
const migrations = await migrationStatus(db, migrationsFolder).catch(() => "unknown");
|
|
23
|
+
return { db: "up", migrations };
|
|
24
|
+
},
|
|
25
|
+
};
|
|
26
|
+
}
|
package/dist/db/index.d.ts
CHANGED
|
@@ -15,6 +15,7 @@ export declare function createDb<S extends Record<string, unknown>>(opts: {
|
|
|
15
15
|
pool: Pool;
|
|
16
16
|
};
|
|
17
17
|
export { ExplainingPool, PGLITE_HINT } from "./explaining-pool.ts";
|
|
18
|
+
export { databaseCheck } from "./health.ts";
|
|
18
19
|
export { migrationStatus } from "./migration-status.ts";
|
|
19
20
|
export { explicitSslMode } from "./ssl.ts";
|
|
20
21
|
export { assertDevDatabase, type DatabaseTargetOptions, endpointOf, isLoopbackUrl, } from "./target.ts";
|
package/dist/db/index.js
CHANGED
|
@@ -26,6 +26,7 @@ export function createDb(opts) {
|
|
|
26
26
|
return { db: drizzle(pool, { schema: opts.schema }), pool };
|
|
27
27
|
}
|
|
28
28
|
export { ExplainingPool, PGLITE_HINT } from "./explaining-pool.js";
|
|
29
|
+
export { databaseCheck } from "./health.js";
|
|
29
30
|
export { migrationStatus } from "./migration-status.js";
|
|
30
31
|
export { explicitSslMode } from "./ssl.js";
|
|
31
32
|
export { assertDevDatabase, endpointOf, isLoopbackUrl, } from "./target.js";
|
package/dist/db/target.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { NODE_ENVS } from "../stack/contracts.js";
|
|
1
2
|
/** True only when `connectionString` parses and its host is this machine. Unparseable is not local. */
|
|
2
3
|
export function isLoopbackUrl(connectionString) {
|
|
3
4
|
if (!connectionString)
|
|
@@ -40,7 +41,7 @@ export function endpointOf(hostOrUrl) {
|
|
|
40
41
|
* Local tooling (dev server, scripts, drizzle-kit, psql) works against a Neon dev branch, and must not reach production by accident — a dev branch's URL and production's differ only in the endpoint. So a remote database is allowed only when `PRODUCTION_DATABASE_HOST` names production and this URL is a different endpoint. Production itself is exempt, a loopback database (the tests' PGlite) always passes, and a command that opted in with `ENV_FILE=…` or `ALLOW_REMOTE_DATABASE=1` is deliberate. Throws; the message names the host only, never the credentials.
|
|
41
42
|
*/
|
|
42
43
|
export function assertDevDatabase(connectionString, { nodeEnv, allowRemote, envFile, productionHost }) {
|
|
43
|
-
if (nodeEnv ===
|
|
44
|
+
if (nodeEnv === NODE_ENVS.production)
|
|
44
45
|
return;
|
|
45
46
|
if (isLoopbackUrl(connectionString))
|
|
46
47
|
return;
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
import type { EnvSource } from "./define-env.ts";
|
|
3
|
+
/**
|
|
4
|
+
* The variables every stack app shares, the first of the app's fragments: `defineEnv({ fragments: [coreEnv, dbEnv, …], schema: { MY_VAR: z.string() } })`. Blank values are treated as absent by `defineEnv`, so no field needs its own preprocessing.
|
|
5
|
+
*/
|
|
6
|
+
export declare const coreEnv: {
|
|
7
|
+
name: string;
|
|
8
|
+
schema: {
|
|
9
|
+
NODE_ENV: z.ZodDefault<z.ZodEnum<{
|
|
10
|
+
readonly development: "development";
|
|
11
|
+
readonly test: "test";
|
|
12
|
+
readonly production: "production";
|
|
13
|
+
}>>;
|
|
14
|
+
APP_URL: z.ZodDefault<z.ZodString>;
|
|
15
|
+
CRON_SECRET: z.ZodOptional<z.ZodString>;
|
|
16
|
+
HEALTH_TOKEN: z.ZodOptional<z.ZodString>;
|
|
17
|
+
TRUSTED_PROXY_HOPS: z.ZodDefault<z.ZodCoercedNumber<unknown>>;
|
|
18
|
+
LOG_LEVEL: z.ZodDefault<z.ZodString>;
|
|
19
|
+
};
|
|
20
|
+
productionRequired: "APP_URL"[];
|
|
21
|
+
};
|
|
22
|
+
/** Whether this is a production run. For the build-time config, which loads before any env schema. */
|
|
23
|
+
export declare function isProductionEnv(source?: EnvSource): boolean;
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
import { NODE_ENVS } from "../stack/contracts.js";
|
|
3
|
+
const schema = {
|
|
4
|
+
// Set by tooling, never by `.env`: next dev/build set it, Vitest sets `test`, Vercel's runtime sets `production`.
|
|
5
|
+
NODE_ENV: z.enum(NODE_ENVS).default(NODE_ENVS.development),
|
|
6
|
+
APP_URL: z.string().default("http://localhost:3000"),
|
|
7
|
+
CRON_SECRET: z.string().optional(),
|
|
8
|
+
HEALTH_TOKEN: z.string().optional(),
|
|
9
|
+
// For `clientIp`: 0 on Vercel, which terminates the proxy chain itself.
|
|
10
|
+
TRUSTED_PROXY_HOPS: z.coerce.number().int().nonnegative().default(0),
|
|
11
|
+
LOG_LEVEL: z.string().default("info"),
|
|
12
|
+
};
|
|
13
|
+
/**
|
|
14
|
+
* The variables every stack app shares, the first of the app's fragments: `defineEnv({ fragments: [coreEnv, dbEnv, …], schema: { MY_VAR: z.string() } })`. Blank values are treated as absent by `defineEnv`, so no field needs its own preprocessing.
|
|
15
|
+
*/
|
|
16
|
+
export const coreEnv = {
|
|
17
|
+
name: "coreEnv",
|
|
18
|
+
schema,
|
|
19
|
+
productionRequired: ["APP_URL"],
|
|
20
|
+
};
|
|
21
|
+
/** Whether this is a production run. For the build-time config, which loads before any env schema. */
|
|
22
|
+
export function isProductionEnv(source = process.env) {
|
|
23
|
+
return source.NODE_ENV === NODE_ENVS.production;
|
|
24
|
+
}
|
package/dist/env/define-env.d.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { z } from "zod";
|
|
2
|
+
import { type EnvFragment } from "../stack/contracts.ts";
|
|
2
3
|
export type EnvSource = Record<string, string | undefined>;
|
|
3
4
|
export interface EnvProblem {
|
|
4
5
|
variable: string;
|
|
@@ -11,20 +12,31 @@ export declare class ConfigError extends Error {
|
|
|
11
12
|
readonly problems: EnvProblem[];
|
|
12
13
|
constructor(problems: EnvProblem[]);
|
|
13
14
|
}
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
/**
|
|
17
|
-
|
|
18
|
-
/**
|
|
19
|
-
|
|
15
|
+
/** What `defineEnv` validates: the fragments the app's packages give, plus the app's own variables. */
|
|
16
|
+
export interface EnvSpec<F extends readonly EnvFragment[] = readonly EnvFragment[], S extends z.ZodRawShape = z.ZodRawShape> {
|
|
17
|
+
/** Each package's variables. A name may be defined once across the fragments and `schema`. */
|
|
18
|
+
fragments?: F;
|
|
19
|
+
/** The app's own variables. */
|
|
20
|
+
schema?: S;
|
|
21
|
+
/** The app's production requirements, on top of each fragment's. */
|
|
22
|
+
productionRequired?: readonly string[];
|
|
23
|
+
/** The app's all-or-none groups, on top of each fragment's. */
|
|
24
|
+
groups?: Readonly<Record<string, readonly string[]>>;
|
|
20
25
|
}
|
|
26
|
+
type UnionToIntersection<U> = (U extends unknown ? (u: U) => void : never) extends (i: infer I) => void ? I : never;
|
|
27
|
+
/** A shape with no variables: the app's schema when it has none, and the fragments' when there are none. */
|
|
28
|
+
type NoShape = Record<never, never>;
|
|
29
|
+
/** Every fragment's schema, as one shape. */
|
|
30
|
+
export type MergedShape<F extends readonly EnvFragment[]> = UnionToIntersection<F[number]["schema"]> extends infer M extends z.ZodRawShape ? M : NoShape;
|
|
21
31
|
/**
|
|
22
|
-
* Validates `source` (default `process.env`, the only place the package reads it) against `schema
|
|
32
|
+
* Validates `source` (default `process.env`, the only place the package reads it) against the fragments' schemas and the app's own `schema`, merged.
|
|
23
33
|
*
|
|
34
|
+
* - A variable defined by two fragments, or by a fragment and the app's schema, throws an `Error` naming both.
|
|
24
35
|
* - Blank values are absent; `<NAME>_FILE` is read when `<NAME>` is unset (both set is an error).
|
|
25
36
|
* - Production requirements are checked against the resolved value before defaults apply, so a development default can never satisfy one.
|
|
26
|
-
* - During a Next build (`NEXT_PHASE=phase-production-build`) or with `SKIP_ENV_VALIDATION=1`, a build is not a boot: production requirements
|
|
27
|
-
* - When the schema has `APP_URL` and it is unset, it is derived on Vercel: from VERCEL_PROJECT_PRODUCTION_URL in production, from VERCEL_BRANCH_URL / VERCEL_URL on a preview
|
|
37
|
+
* - During a Next build (`NEXT_PHASE=phase-production-build`) or with `SKIP_ENV_VALIDATION=1`, a build is not a boot: production requirements and groups are not enforced, and an unset variable with a fragment's build placeholder takes it, but defaults still apply. With `NODE_ENV=production`, `SKIP_ENV_VALIDATION` is ignored outside the build phase.
|
|
38
|
+
* - When the merged schema has `APP_URL` and it is unset, it is derived on Vercel: from VERCEL_PROJECT_PRODUCTION_URL in production, from VERCEL_BRANCH_URL / VERCEL_URL on a preview.
|
|
28
39
|
* - Throws one `ConfigError` listing every problem.
|
|
29
40
|
*/
|
|
30
|
-
export declare function defineEnv<S extends z.ZodRawShape>(spec: EnvSpec<S>, rawSource?: EnvSource): z.infer<z.ZodObject<S>>;
|
|
41
|
+
export declare function defineEnv<const F extends readonly EnvFragment[] = [], S extends z.ZodRawShape = NoShape>(spec: EnvSpec<F, S>, rawSource?: EnvSource): z.infer<z.ZodObject<MergedShape<F> & S>>;
|
|
42
|
+
export {};
|
package/dist/env/define-env.js
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { readFileSync } from "node:fs";
|
|
2
2
|
import { z } from "zod";
|
|
3
|
+
import { NODE_ENVS, VERCEL_TARGET } from "../stack/contracts.js";
|
|
3
4
|
/**
|
|
4
5
|
* Thrown by `defineEnv` with every problem found, not just the first. The message names each bad variable and says what is wrong with it; it never contains a variable's value, because values can be secrets.
|
|
5
6
|
*/
|
|
@@ -13,8 +14,6 @@ export class ConfigError extends Error {
|
|
|
13
14
|
this.problems = problems;
|
|
14
15
|
}
|
|
15
16
|
}
|
|
16
|
-
/** Stands in for a connection string during a build, which never opens a connection. */
|
|
17
|
-
const BUILD_PLACEHOLDER_DATABASE_URL = "postgres://unused:unused@127.0.0.1:1/unused";
|
|
18
17
|
const TRAILING_NEWLINES = /[\r\n]+$/;
|
|
19
18
|
const isBlank = (value) => value === undefined || value.trim() === "";
|
|
20
19
|
/**
|
|
@@ -54,36 +53,92 @@ function resolve(name, source, problems) {
|
|
|
54
53
|
function withVercelAppUrl(source) {
|
|
55
54
|
if (!isBlank(source.APP_URL) || !isBlank(source.APP_URL_FILE))
|
|
56
55
|
return source;
|
|
57
|
-
const host = source.VERCEL_ENV ===
|
|
56
|
+
const host = source.VERCEL_ENV === VERCEL_TARGET.production
|
|
58
57
|
? (source.VERCEL_PROJECT_PRODUCTION_URL ?? "").trim()
|
|
59
|
-
: source.VERCEL_ENV ===
|
|
58
|
+
: source.VERCEL_ENV === VERCEL_TARGET.preview
|
|
60
59
|
? (source.VERCEL_BRANCH_URL ?? "").trim() || (source.VERCEL_URL ?? "").trim()
|
|
61
60
|
: "";
|
|
62
61
|
return host === "" ? source : { ...source, APP_URL: `https://${host}` };
|
|
63
62
|
}
|
|
64
63
|
/**
|
|
65
|
-
*
|
|
64
|
+
* Merges the fragments and the app's own schema into one. A fragment is named by its `name` (`coreEnv`). A package's variable is the package's, its default included: the app sets its value in the environment and never defines it again. A variable defined twice, or a requirement or group member that nothing defines, is a mistake in the app's code, not its environment, so it throws a plain `Error` naming each one.
|
|
65
|
+
*/
|
|
66
|
+
function merge(spec) {
|
|
67
|
+
const app = {
|
|
68
|
+
name: "the app's schema",
|
|
69
|
+
schema: spec.schema ?? {},
|
|
70
|
+
productionRequired: spec.productionRequired,
|
|
71
|
+
groups: spec.groups,
|
|
72
|
+
};
|
|
73
|
+
const sources = [
|
|
74
|
+
...(spec.fragments ?? []).map((fragment, i) => {
|
|
75
|
+
// A fragment from plain JavaScript may lack its name; its position names it then.
|
|
76
|
+
const label = fragment.name || `fragment ${i + 1}`;
|
|
77
|
+
return { label, whose: `${label}'s`, fragment };
|
|
78
|
+
}),
|
|
79
|
+
{ label: "the app's schema", whose: "the app's", fragment: app },
|
|
80
|
+
];
|
|
81
|
+
const mistakes = [];
|
|
82
|
+
const definedBy = new Map();
|
|
83
|
+
const merged = { shape: {}, productionRequired: [], groups: [], placeholders: {} };
|
|
84
|
+
for (const { label, fragment } of sources) {
|
|
85
|
+
for (const [name, type] of Object.entries(fragment.schema)) {
|
|
86
|
+
const first = definedBy.get(name);
|
|
87
|
+
if (first === undefined) {
|
|
88
|
+
definedBy.set(name, label);
|
|
89
|
+
merged.shape[name] = type;
|
|
90
|
+
}
|
|
91
|
+
else {
|
|
92
|
+
mistakes.push(fragment === app
|
|
93
|
+
? `${name} is defined by ${first}: remove it from the app's schema, and set its value in the environment`
|
|
94
|
+
: `${name} is defined twice: by ${first} and ${label}`);
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
merged.productionRequired.push(...(fragment.productionRequired ?? []));
|
|
98
|
+
merged.groups.push(...Object.entries(fragment.groups ?? {}));
|
|
99
|
+
Object.assign(merged.placeholders, fragment.buildPlaceholders);
|
|
100
|
+
}
|
|
101
|
+
for (const { whose, fragment } of sources) {
|
|
102
|
+
const named = [
|
|
103
|
+
...(fragment.productionRequired ?? []).map((name) => ({ name, by: "productionRequired" })),
|
|
104
|
+
...Object.entries(fragment.groups ?? {}).flatMap(([group, members]) => members.map((name) => ({ name, by: `group ${group}` }))),
|
|
105
|
+
];
|
|
106
|
+
for (const { name, by } of named) {
|
|
107
|
+
if (definedBy.has(name))
|
|
108
|
+
continue;
|
|
109
|
+
mistakes.push(`${name} is named by ${whose} ${by}, but no fragment or the app's schema defines it`);
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
if (mistakes.length > 0)
|
|
113
|
+
throw new Error(`defineEnv: ${mistakes.join("; ")}`);
|
|
114
|
+
return merged;
|
|
115
|
+
}
|
|
116
|
+
/**
|
|
117
|
+
* Validates `source` (default `process.env`, the only place the package reads it) against the fragments' schemas and the app's own `schema`, merged.
|
|
66
118
|
*
|
|
119
|
+
* - A variable defined by two fragments, or by a fragment and the app's schema, throws an `Error` naming both.
|
|
67
120
|
* - Blank values are absent; `<NAME>_FILE` is read when `<NAME>` is unset (both set is an error).
|
|
68
121
|
* - Production requirements are checked against the resolved value before defaults apply, so a development default can never satisfy one.
|
|
69
|
-
* - During a Next build (`NEXT_PHASE=phase-production-build`) or with `SKIP_ENV_VALIDATION=1`, a build is not a boot: production requirements
|
|
70
|
-
* - When the schema has `APP_URL` and it is unset, it is derived on Vercel: from VERCEL_PROJECT_PRODUCTION_URL in production, from VERCEL_BRANCH_URL / VERCEL_URL on a preview
|
|
122
|
+
* - During a Next build (`NEXT_PHASE=phase-production-build`) or with `SKIP_ENV_VALIDATION=1`, a build is not a boot: production requirements and groups are not enforced, and an unset variable with a fragment's build placeholder takes it, but defaults still apply. With `NODE_ENV=production`, `SKIP_ENV_VALIDATION` is ignored outside the build phase.
|
|
123
|
+
* - When the merged schema has `APP_URL` and it is unset, it is derived on Vercel: from VERCEL_PROJECT_PRODUCTION_URL in production, from VERCEL_BRANCH_URL / VERCEL_URL on a preview.
|
|
71
124
|
* - Throws one `ConfigError` listing every problem.
|
|
72
125
|
*/
|
|
73
126
|
export function defineEnv(spec, rawSource = process.env) {
|
|
74
|
-
const
|
|
127
|
+
const { shape, productionRequired, groups, placeholders } = merge(spec);
|
|
128
|
+
const source = "APP_URL" in shape ? withVercelAppUrl(rawSource) : rawSource;
|
|
75
129
|
const problems = [];
|
|
76
130
|
const resolved = {};
|
|
77
|
-
for (const name of Object.keys(
|
|
131
|
+
for (const name of Object.keys(shape)) {
|
|
78
132
|
resolved[name] = resolve(name, source, problems);
|
|
79
133
|
}
|
|
80
|
-
// SKIP_ENV_VALIDATION is for builds and tooling. A production server that inherited it would boot on development defaults (a public
|
|
134
|
+
// SKIP_ENV_VALIDATION is for builds and tooling. A production server that inherited it would boot on development defaults (a public development secret), so production honours it only in the build phase.
|
|
81
135
|
const building = source.NEXT_PHASE === "phase-production-build";
|
|
82
|
-
const skipValidation = building || (source.SKIP_ENV_VALIDATION === "1" && source.NODE_ENV !==
|
|
83
|
-
if (skipValidation
|
|
84
|
-
|
|
136
|
+
const skipValidation = building || (source.SKIP_ENV_VALIDATION === "1" && source.NODE_ENV !== NODE_ENVS.production);
|
|
137
|
+
if (skipValidation) {
|
|
138
|
+
for (const [name, placeholder] of Object.entries(placeholders))
|
|
139
|
+
resolved[name] ??= placeholder;
|
|
85
140
|
}
|
|
86
|
-
const parsed = z.object(
|
|
141
|
+
const parsed = z.object(shape).safeParse(resolved);
|
|
87
142
|
// One problem per variable: a bad `_FILE` also leaves its plain name unset, and a missing production secret may also fail the schema.
|
|
88
143
|
const reported = new Set(problems.flatMap((p) => [p.variable, p.variable.replace(/_FILE$/, "")]));
|
|
89
144
|
if (!parsed.success) {
|
|
@@ -96,7 +151,7 @@ export function defineEnv(spec, rawSource = process.env) {
|
|
|
96
151
|
}
|
|
97
152
|
}
|
|
98
153
|
if (!skipValidation) {
|
|
99
|
-
for (const [group, members] of
|
|
154
|
+
for (const [group, members] of groups) {
|
|
100
155
|
const present = members.filter((name) => resolved[name] !== undefined);
|
|
101
156
|
if (present.length === 0 || present.length === members.length)
|
|
102
157
|
continue;
|
|
@@ -107,8 +162,8 @@ export function defineEnv(spec, rawSource = process.env) {
|
|
|
107
162
|
});
|
|
108
163
|
}
|
|
109
164
|
}
|
|
110
|
-
if (resolved.NODE_ENV ===
|
|
111
|
-
for (const name of
|
|
165
|
+
if (resolved.NODE_ENV === NODE_ENVS.production) {
|
|
166
|
+
for (const name of productionRequired) {
|
|
112
167
|
if (resolved[name] === undefined && !reported.has(name)) {
|
|
113
168
|
problems.push({ variable: name, problem: "is required when NODE_ENV is production" });
|
|
114
169
|
}
|
package/dist/env/index.d.ts
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
export {
|
|
1
|
+
export { coreEnv, isProductionEnv } from "./core-env.ts";
|
|
2
|
+
export { ConfigError, defineEnv, type EnvProblem, type EnvSource, type EnvSpec, type MergedShape, } from "./define-env.ts";
|
|
2
3
|
export { loadEnvFile } from "./load-env-file.ts";
|
|
3
|
-
export { isProductionEnv, type StackEnv, stackEnv, stackEnvSchema, stackGroups, stackProductionRequired, } from "./stack-env.ts";
|
package/dist/env/index.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
+
export { coreEnv, isProductionEnv } from "./core-env.js";
|
|
1
2
|
export { ConfigError, defineEnv, } from "./define-env.js";
|
|
2
3
|
export { loadEnvFile } from "./load-env-file.js";
|
|
3
|
-
export { isProductionEnv, stackEnv, stackEnvSchema, stackGroups, stackProductionRequired, } from "./stack-env.js";
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Who the caller is, read from standard forwarded headers in this one place. No vendor-specific header (Cloudflare's, Vercel's) is read: the proxy in front of the app is infrastructure, and `X-Forwarded-For` already carries the value.
|
|
3
|
+
*
|
|
4
|
+
* The client is the first entry a trusted proxy did not add: with `hops` trusted proxies in front, the Nth-from-last entry in `X-Forwarded-For`. Trusting the *first* entry instead is the classic spoof — a caller can send any `X-Forwarded-For` they like, and only the entries the proxies themselves appended can be believed. Hence counting from the right. Vercel terminates the chain itself, so `hops` is 0 there.
|
|
5
|
+
*/
|
|
6
|
+
export declare function clientIp(headers: Headers, hops: number): string | null;
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Who the caller is, read from standard forwarded headers in this one place. No vendor-specific header (Cloudflare's, Vercel's) is read: the proxy in front of the app is infrastructure, and `X-Forwarded-For` already carries the value.
|
|
3
|
+
*
|
|
4
|
+
* The client is the first entry a trusted proxy did not add: with `hops` trusted proxies in front, the Nth-from-last entry in `X-Forwarded-For`. Trusting the *first* entry instead is the classic spoof — a caller can send any `X-Forwarded-For` they like, and only the entries the proxies themselves appended can be believed. Hence counting from the right. Vercel terminates the chain itself, so `hops` is 0 there.
|
|
5
|
+
*/
|
|
6
|
+
export function clientIp(headers, hops) {
|
|
7
|
+
const forwarded = headers.get("x-forwarded-for");
|
|
8
|
+
if (forwarded !== null) {
|
|
9
|
+
const entries = forwarded
|
|
10
|
+
.split(",")
|
|
11
|
+
.map((entry) => entry.trim())
|
|
12
|
+
.filter((entry) => entry.length > 0);
|
|
13
|
+
if (entries.length > 0) {
|
|
14
|
+
// Clamped: a request that arrived with fewer hops than configured is not a reason to return nothing, and the left-most entry is the best remaining guess.
|
|
15
|
+
const index = Math.max(entries.length - 1 - hops, 0);
|
|
16
|
+
return entries[index];
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
// Standard, non-vendor fallback only.
|
|
20
|
+
return headers.get("x-real-ip") ?? null;
|
|
21
|
+
}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Where to send someone after signing in, from a `?next=` they could have been handed by anyone. Only a path on this site is kept; anything else becomes `fallback`, so a sign-in link can never be turned into a redirect to another origin.
|
|
3
|
+
*
|
|
4
|
+
* Kept: a string starting with a single `/`. Refused, as well as anything that is not a string:
|
|
5
|
+
* - `//host` and `/\host`: browsers read both as protocol-relative URLs to another host;
|
|
6
|
+
* - any backslash: the URL parser turns it into `/`;
|
|
7
|
+
* - control characters: the URL parser strips tabs and newlines, so `/\t/host` becomes `//host`;
|
|
8
|
+
* - `https:`, `javascript:` and every other scheme: they do not start with `/`.
|
|
9
|
+
* Then the path is resolved as a browser would, which removes dot segments (`.`, `..`, `%2e`): it must stay on the origin it is resolved against, and its resolved path must not itself start with `//` — `/..//host` and `/%2e//host` resolve to `//host`, which a router that writes the path back would follow off-site. What is returned is that resolved path, query and fragment, so a caller only ever passes on what was checked.
|
|
10
|
+
*/
|
|
11
|
+
export declare function safeNext(raw: unknown, fallback?: string): string;
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Where to send someone after signing in, from a `?next=` they could have been handed by anyone. Only a path on this site is kept; anything else becomes `fallback`, so a sign-in link can never be turned into a redirect to another origin.
|
|
3
|
+
*
|
|
4
|
+
* Kept: a string starting with a single `/`. Refused, as well as anything that is not a string:
|
|
5
|
+
* - `//host` and `/\host`: browsers read both as protocol-relative URLs to another host;
|
|
6
|
+
* - any backslash: the URL parser turns it into `/`;
|
|
7
|
+
* - control characters: the URL parser strips tabs and newlines, so `/\t/host` becomes `//host`;
|
|
8
|
+
* - `https:`, `javascript:` and every other scheme: they do not start with `/`.
|
|
9
|
+
* Then the path is resolved as a browser would, which removes dot segments (`.`, `..`, `%2e`): it must stay on the origin it is resolved against, and its resolved path must not itself start with `//` — `/..//host` and `/%2e//host` resolve to `//host`, which a router that writes the path back would follow off-site. What is returned is that resolved path, query and fragment, so a caller only ever passes on what was checked.
|
|
10
|
+
*/
|
|
11
|
+
export function safeNext(raw, fallback = "/") {
|
|
12
|
+
if (typeof raw !== "string")
|
|
13
|
+
return fallback;
|
|
14
|
+
if (!raw.startsWith("/") || raw.startsWith("//"))
|
|
15
|
+
return fallback;
|
|
16
|
+
// biome-ignore lint/suspicious/noControlCharactersInRegex: refusing control characters is the point.
|
|
17
|
+
if (/[\\\u0000-\u001f\u007f]/.test(raw))
|
|
18
|
+
return fallback;
|
|
19
|
+
const base = "http://same-site.invalid";
|
|
20
|
+
let url;
|
|
21
|
+
try {
|
|
22
|
+
url = new URL(raw, base);
|
|
23
|
+
}
|
|
24
|
+
catch {
|
|
25
|
+
return fallback;
|
|
26
|
+
}
|
|
27
|
+
if (url.origin !== base || url.pathname.startsWith("//"))
|
|
28
|
+
return fallback;
|
|
29
|
+
return `${url.pathname}${url.search}${url.hash}`;
|
|
30
|
+
}
|
package/dist/index.d.ts
CHANGED
|
@@ -1 +1,2 @@
|
|
|
1
|
-
export {};
|
|
1
|
+
export type { Block, BlockFile, BuildStep, Command, CommandContext, DoctorCheck, DoctorFacts, Env, EnvFragment, EnvVarMeta, ExecOptions, ExecResult, Finding, Gate, GateResult, HealthCheck, NodeEnv, Severity, StackConfig, StackPackage, VariableOf, VercelTarget, } from "./stack/contracts.ts";
|
|
2
|
+
export { BLOCK_FILES, BUILTIN_PACKAGE, defineStack, NODE_ENVS, packageBlocks, SEVERITY, STACK_CONFIG_FILE, VERCEL_TARGET, } from "./stack/contracts.ts";
|
package/dist/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export {};
|
|
1
|
+
export { BLOCK_FILES, BUILTIN_PACKAGE, defineStack, NODE_ENVS, packageBlocks, SEVERITY, STACK_CONFIG_FILE, VERCEL_TARGET, } from "./stack/contracts.js";
|
package/dist/next/api.d.ts
CHANGED
|
@@ -1,10 +1,12 @@
|
|
|
1
|
-
import type {
|
|
1
|
+
import type { Gate } from "../stack/contracts.ts";
|
|
2
2
|
/**
|
|
3
|
-
* The shell every API route runs in:
|
|
3
|
+
* The shell every API route runs in: the gate, the request guards, the handler, and the envelope for whatever it throws. Written once so route files cannot drift on it.
|
|
4
|
+
*
|
|
5
|
+
* The gate decides who the caller is: its 401 is answered `unauthenticated`, its 404 `not_found` (never a 403, so a route the caller may not use does not announce itself), and its principal is handed to the handler. A gate that throws is a bug like any other.
|
|
4
6
|
*
|
|
5
7
|
* Every failure answers `{ error: { code, message } }`. An `ApiError` is answered as it says; that is how `readJson` reports the request body (400 `invalid_json`, 422 `invalid_input`). Anything else is a bug, even a SyntaxError or a ZodError from the route's own code, and becomes a 500 with a fixed message: what was thrown is logged for the operator and never sent to the caller.
|
|
6
8
|
*
|
|
7
|
-
* `CRON_SECRET` and `HEALTH_TOKEN` are never read here. This wrapper
|
|
9
|
+
* `CRON_SECRET` and `HEALTH_TOKEN` are never read here. This wrapper admits only what its gate admits, so neither secret opens an API route.
|
|
8
10
|
*/
|
|
9
11
|
/** An error a route throws on purpose: its message is written for the caller and is sent as is. */
|
|
10
12
|
export declare class ApiError extends Error {
|
|
@@ -49,11 +51,10 @@ export type BodySchema<T> = {
|
|
|
49
51
|
*/
|
|
50
52
|
export declare function readJson(req: Request): Promise<unknown>;
|
|
51
53
|
export declare function readJson<T>(req: Request, schema: BodySchema<T>): Promise<T>;
|
|
52
|
-
export type ApiHandlerOptions = {
|
|
53
|
-
auth: StackAuth;
|
|
54
|
+
export type ApiHandlerOptions<P> = {
|
|
54
55
|
/** What a failure logs as: `"PUT /api/v1/things/:id"`. */
|
|
55
56
|
label: string;
|
|
56
|
-
/**
|
|
57
|
-
|
|
57
|
+
/** Who may call the route; what it admits is the handler's `principal`. */
|
|
58
|
+
gate: Gate<P>;
|
|
58
59
|
};
|
|
59
|
-
export declare function apiHandler<C = unknown>(opts: ApiHandlerOptions
|
|
60
|
+
export declare function apiHandler<P, C = unknown>(opts: ApiHandlerOptions<P>, fn: (req: Request, ctx: C, principal: P) => Promise<Response>): (req: Request, ctx: C) => Promise<Response>;
|