@wwchen/stack 0.6.3 → 0.7.0
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 +9 -8
- package/blocks/env.example +1 -2
- package/dist/auth/better-auth/index.d.ts +2 -316
- package/dist/auth/better-auth/index.js +2 -237
- package/dist/auth/index.d.ts +2 -58
- package/dist/auth/index.js +2 -120
- package/dist/auth/proxy.d.ts +2 -14
- package/dist/auth/proxy.js +2 -50
- package/dist/cli/context.d.ts +6 -3
- package/dist/cli/context.js +3 -0
- package/dist/cli/db.d.ts +3 -0
- package/dist/cli/db.js +26 -0
- package/dist/cli/index.js +14 -3
- package/dist/cli/migrate-suite.d.ts +2 -0
- package/dist/cli/migrate-suite.js +787 -0
- package/dist/cli/neon.d.ts +11 -44
- package/dist/cli/neon.js +15 -56
- package/dist/cli/sync-blocks.d.ts +1 -3
- package/dist/cli/sync-blocks.js +2 -6
- package/dist/cli/vercel-build.js +5 -16
- package/dist/configs/vitest.js +3 -7
- package/dist/connections/index.d.ts +2 -8
- package/dist/connections/index.js +3 -9
- package/dist/connections/providers.d.ts +1 -3
- package/dist/connections/table.d.ts +2 -3
- package/dist/connections/table.js +1 -2
- package/dist/db/explaining-pool.d.ts +1 -6
- package/dist/db/explaining-pool.js +3 -10
- package/dist/db/index.d.ts +1 -3
- package/dist/db/index.js +5 -13
- package/dist/db/migration-status.d.ts +1 -4
- package/dist/db/migration-status.js +1 -4
- package/dist/db/schema-changes.d.ts +13 -0
- package/dist/db/schema-changes.js +99 -0
- package/dist/db/ssl.d.ts +1 -5
- package/dist/db/ssl.js +1 -5
- package/dist/db/target.d.ts +2 -9
- package/dist/db/target.js +2 -9
- package/dist/db/testing/index.d.ts +3 -7
- package/dist/db/testing/index.js +3 -7
- package/dist/db/testing/isolate.js +1 -2
- package/dist/db/testing/pglite.d.ts +2 -6
- package/dist/db/testing/pglite.js +2 -6
- package/dist/env/define-env.d.ts +3 -9
- package/dist/env/define-env.js +6 -16
- package/dist/env/load-env-file.d.ts +4 -9
- package/dist/env/load-env-file.js +5 -11
- package/dist/env/stack-env.d.ts +1 -3
- package/dist/env/stack-env.js +3 -7
- package/dist/env/testing.d.ts +1 -3
- package/dist/env/testing.js +2 -5
- package/dist/http/guards.d.ts +3 -10
- package/dist/http/guards.js +4 -12
- package/dist/jobs/index.d.ts +2 -9
- package/dist/jobs/index.js +2 -9
- package/dist/mail/index.d.ts +4 -45
- package/dist/mail/index.js +4 -97
- package/dist/next/api.d.ts +7 -19
- package/dist/next/api.js +6 -15
- package/dist/next/config.js +10 -32
- package/dist/next/cron.d.ts +2 -6
- package/dist/next/cron.js +3 -8
- package/dist/next/health.d.ts +3 -8
- package/dist/next/health.js +3 -8
- package/dist/testing/next.d.ts +1 -4
- package/dist/testing/next.js +2 -7
- package/dist/ui/app.css +5 -16
- package/dist/ui/globals.css +6 -20
- package/dist/ui/icons.d.ts +1 -3
- package/dist/ui/icons.js +3 -10
- package/dist/ui/index.d.ts +4 -12
- package/dist/ui/index.js +4 -12
- package/dist/ui/theme.d.ts +3 -9
- package/dist/ui/theme.js +3 -9
- package/package.json +15 -9
- package/dist/auth/better-auth/tables.d.ts +0 -628
- package/dist/auth/better-auth/tables.js +0 -76
- package/dist/auth/better-auth/users.d.ts +0 -27
- package/dist/auth/better-auth/users.js +0 -128
- package/dist/auth/safe-next.d.ts +0 -17
- package/dist/auth/safe-next.js +0 -36
- package/dist/auth/types.d.ts +0 -47
- package/dist/auth/types.js +0 -5
- package/dist/http/client-ip.d.ts +0 -12
- package/dist/http/client-ip.js +0 -28
- package/dist/http/rate-limit.d.ts +0 -34
- package/dist/http/rate-limit.js +0 -79
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
import { readFile } from "node:fs/promises";
|
|
2
|
+
import { join } from "node:path";
|
|
3
|
+
/** The schemas an app's migrations cover: the template's `schemaFilter`. */
|
|
4
|
+
const SCHEMA_FILTER = ["public"];
|
|
5
|
+
/** drizzle-kit is an optional peer: only drift detection loads it, so an app without it can still use the rest of the stack. */
|
|
6
|
+
async function loadDrizzleKit() {
|
|
7
|
+
try {
|
|
8
|
+
return await import("drizzle-kit/api");
|
|
9
|
+
}
|
|
10
|
+
catch (error) {
|
|
11
|
+
throw new Error("drizzle-kit could not be loaded: install drizzle-kit 0.31.11 as a devDependency of the app and run `pnpm install`.", { cause: error });
|
|
12
|
+
}
|
|
13
|
+
}
|
|
14
|
+
/** The snapshot of the migration the journal lists last (drizzle-kit names it by the tag's prefix), or undefined when nothing has been generated. */
|
|
15
|
+
async function latestSnapshot(migrationsFolder) {
|
|
16
|
+
let journal;
|
|
17
|
+
try {
|
|
18
|
+
journal = JSON.parse(await readFile(join(migrationsFolder, "meta", "_journal.json"), "utf8"));
|
|
19
|
+
}
|
|
20
|
+
catch (error) {
|
|
21
|
+
if (error.code === "ENOENT")
|
|
22
|
+
return undefined;
|
|
23
|
+
throw error;
|
|
24
|
+
}
|
|
25
|
+
const last = journal.entries?.at(-1);
|
|
26
|
+
if (!last)
|
|
27
|
+
return undefined;
|
|
28
|
+
const file = join(migrationsFolder, "meta", `${last.tag.split("_")[0]}_snapshot.json`);
|
|
29
|
+
return JSON.parse(await readFile(file, "utf8"));
|
|
30
|
+
}
|
|
31
|
+
/**
|
|
32
|
+
* The SQL `drizzle-kit generate` would write for `schema` (the app's `src/db/schema.ts` exports) against the latest migration in `migrationsFolder`: empty when the migrations are current. Only tables in `public` count, as in the template's drizzle config. Assumes that config sets no `casing` (the template's does not): with one, the names here would differ from what `generate` writes.
|
|
33
|
+
*/
|
|
34
|
+
export async function pendingStatements(schema, migrationsFolder) {
|
|
35
|
+
const kit = await loadDrizzleKit();
|
|
36
|
+
const current = kit.generateDrizzleJson(schema, undefined, SCHEMA_FILTER);
|
|
37
|
+
const previous = (await latestSnapshot(migrationsFolder)) ??
|
|
38
|
+
kit.generateDrizzleJson({}, undefined, SCHEMA_FILTER);
|
|
39
|
+
try {
|
|
40
|
+
return await kit.generateMigration(previous, current);
|
|
41
|
+
}
|
|
42
|
+
catch (error) {
|
|
43
|
+
// drizzle-kit asks whether a dropped and an added table or column are a rename, and cannot ask without a terminal.
|
|
44
|
+
if (error instanceof Error && /Interactive prompts require a TTY/.test(error.message)) {
|
|
45
|
+
throw new Error("the schema both drops and adds a table or column, and only a person can say whether it is a rename: run `drizzle-kit generate` in a terminal.", { cause: error });
|
|
46
|
+
}
|
|
47
|
+
throw error;
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
/** Quoted identifiers and string literals, blanked so a name or value never reads as a keyword. */
|
|
51
|
+
const QUOTED = /"(?:[^"]|"")*"|'(?:[^']|'')*'/g;
|
|
52
|
+
/** A table name as drizzle-kit writes it: `"t"` or `"schema"."t"`, quoted or bare. */
|
|
53
|
+
const NAME = String.raw `(?:"(?:[^"]|"")*"|\w+)`;
|
|
54
|
+
const TABLE = String.raw `(${NAME}(?:\s*\.\s*${NAME})?)`;
|
|
55
|
+
const CREATE_TABLE = new RegExp(String.raw `^CREATE\s+TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?${TABLE}`, "i");
|
|
56
|
+
const ADD_CONSTRAINT = new RegExp(String.raw `^ALTER\s+TABLE\s+(?:ONLY\s+)?${TABLE}\s+ADD\s+CONSTRAINT\b`, "i");
|
|
57
|
+
const UNIQUE_INDEX = new RegExp(String.raw `^CREATE\s+UNIQUE\s+INDEX\b[\s\S]*?\bON\s+(?:ONLY\s+)?${TABLE}`, "i");
|
|
58
|
+
/** One spelling per table: unquoted, and without the default `public.` schema. */
|
|
59
|
+
function tableKey(name) {
|
|
60
|
+
const parts = name
|
|
61
|
+
.split(/\s*\.\s*/)
|
|
62
|
+
.map((part) => part.replace(/^"|"$/g, "").replaceAll('""', '"'));
|
|
63
|
+
if (parts.length === 2 && parts[0] === "public")
|
|
64
|
+
parts.shift();
|
|
65
|
+
return parts.join(".");
|
|
66
|
+
}
|
|
67
|
+
/**
|
|
68
|
+
* The statements in a drizzle-kit migration that an old deployment cannot survive. The old deployment keeps serving while the build migrates, so a migration may only add what the old code ignores. Flagged:
|
|
69
|
+
* - each `DROP` (a table, column, index, constraint, default…), except `DROP NOT NULL`, which only loosens a column;
|
|
70
|
+
* - each `RENAME`;
|
|
71
|
+
* - `ADD COLUMN … NOT NULL` without a default: the old code's inserts leave it empty;
|
|
72
|
+
* - `SET NOT NULL` and `SET DATA TYPE` on an existing column: the old code's writes may no longer fit;
|
|
73
|
+
* - `ADD CONSTRAINT` (any kind) and `CREATE UNIQUE INDEX` on a table the same migration did not create: they can reject the old code's inserts. drizzle-kit writes a new table's foreign keys as separate `ADD CONSTRAINT` statements, and those pass.
|
|
74
|
+
*/
|
|
75
|
+
export function contractStatements(sql) {
|
|
76
|
+
const statements = sql
|
|
77
|
+
.split("--> statement-breakpoint")
|
|
78
|
+
.map((statement) => statement.trim())
|
|
79
|
+
.filter(Boolean);
|
|
80
|
+
const created = new Set(statements.flatMap((statement) => {
|
|
81
|
+
const name = CREATE_TABLE.exec(statement)?.[1];
|
|
82
|
+
return name ? [tableKey(name)] : [];
|
|
83
|
+
}));
|
|
84
|
+
return statements.filter((statement) => {
|
|
85
|
+
const code = statement.replace(QUOTED, '""');
|
|
86
|
+
if (/\bDROP\b(?!\s+NOT\s+NULL\b)/i.test(code))
|
|
87
|
+
return true;
|
|
88
|
+
if (/\bRENAME\b/i.test(code))
|
|
89
|
+
return true;
|
|
90
|
+
if (/\bSET\s+(NOT\s+NULL|DATA\s+TYPE)\b/i.test(code))
|
|
91
|
+
return true;
|
|
92
|
+
const constrained = (ADD_CONSTRAINT.exec(statement) ?? UNIQUE_INDEX.exec(statement))?.[1];
|
|
93
|
+
if (constrained !== undefined && !created.has(tableKey(constrained)))
|
|
94
|
+
return true;
|
|
95
|
+
return (/\bADD\s+COLUMN\b/i.test(code) &&
|
|
96
|
+
/\bNOT\s+NULL\b/i.test(code) &&
|
|
97
|
+
!/\b(DEFAULT|GENERATED|SERIAL|SMALLSERIAL|BIGSERIAL)\b/i.test(code));
|
|
98
|
+
});
|
|
99
|
+
}
|
package/dist/db/ssl.d.ts
CHANGED
|
@@ -1,8 +1,4 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* Neon's connection strings say `sslmode=require`. pg 8 already treats `prefer`, `require` and
|
|
3
|
-
* `verify-ca` as `verify-full`, and says so on every new connection with a "SECURITY WARNING" that
|
|
4
|
-
* v9 will weaken them; on Vercel that lands in the runtime logs at error level on every cold start.
|
|
5
|
-
* Spelling out `verify-full` keeps exactly today's checking and silences the warning. Any other
|
|
6
|
-
* mode, or no mode, is left as it is; so is a string that is not a URL.
|
|
2
|
+
* Neon's connection strings say `sslmode=require`. pg 8 already treats `prefer`, `require` and `verify-ca` as `verify-full`, and says so on every new connection with a "SECURITY WARNING" that v9 will weaken them; on Vercel that lands in the runtime logs at error level on every cold start. Spelling out `verify-full` keeps exactly today's checking and silences the warning. Any other mode, or no mode, is left as it is; so is a string that is not a URL.
|
|
7
3
|
*/
|
|
8
4
|
export declare function explicitSslMode(connectionString: string): string;
|
package/dist/db/ssl.js
CHANGED
|
@@ -1,9 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* Neon's connection strings say `sslmode=require`. pg 8 already treats `prefer`, `require` and
|
|
3
|
-
* `verify-ca` as `verify-full`, and says so on every new connection with a "SECURITY WARNING" that
|
|
4
|
-
* v9 will weaken them; on Vercel that lands in the runtime logs at error level on every cold start.
|
|
5
|
-
* Spelling out `verify-full` keeps exactly today's checking and silences the warning. Any other
|
|
6
|
-
* mode, or no mode, is left as it is; so is a string that is not a URL.
|
|
2
|
+
* Neon's connection strings say `sslmode=require`. pg 8 already treats `prefer`, `require` and `verify-ca` as `verify-full`, and says so on every new connection with a "SECURITY WARNING" that v9 will weaken them; on Vercel that lands in the runtime logs at error level on every cold start. Spelling out `verify-full` keeps exactly today's checking and silences the warning. Any other mode, or no mode, is left as it is; so is a string that is not a URL.
|
|
7
3
|
*/
|
|
8
4
|
export function explicitSslMode(connectionString) {
|
|
9
5
|
let url;
|
package/dist/db/target.d.ts
CHANGED
|
@@ -1,9 +1,7 @@
|
|
|
1
1
|
/** True only when `connectionString` parses and its host is this machine. Unparseable is not local. */
|
|
2
2
|
export declare function isLoopbackUrl(connectionString: string | undefined): boolean;
|
|
3
3
|
/**
|
|
4
|
-
* A Neon endpoint's identity, the same for its pooled and direct hosts:
|
|
5
|
-
* `ep-x-123-pooler.us-east-2.aws.neon.tech` and `ep-x-123.us-east-2.aws.neon.tech` are one database.
|
|
6
|
-
* Accepts a bare host or a whole connection string.
|
|
4
|
+
* A Neon endpoint's identity, the same for its pooled and direct hosts: `ep-x-123-pooler.us-east-2.aws.neon.tech` and `ep-x-123.us-east-2.aws.neon.tech` are one database. Accepts a bare host or a whole connection string.
|
|
7
5
|
*/
|
|
8
6
|
export declare function endpointOf(hostOrUrl: string): string;
|
|
9
7
|
export type DatabaseTargetOptions = {
|
|
@@ -16,11 +14,6 @@ export type DatabaseTargetOptions = {
|
|
|
16
14
|
productionHost: string | undefined;
|
|
17
15
|
};
|
|
18
16
|
/**
|
|
19
|
-
* Local tooling (dev server, scripts, drizzle-kit, psql) works against a Neon dev branch, and must
|
|
20
|
-
* not reach production by accident — a dev branch's URL and production's differ only in the
|
|
21
|
-
* endpoint. So a remote database is allowed only when `PRODUCTION_DATABASE_HOST` names production
|
|
22
|
-
* and this URL is a different endpoint. Production itself is exempt, a loopback database (the tests'
|
|
23
|
-
* PGlite) always passes, and a command that opted in with `ENV_FILE=…` or `ALLOW_REMOTE_DATABASE=1`
|
|
24
|
-
* is deliberate. Throws; the message names the host only, never the credentials.
|
|
17
|
+
* 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.
|
|
25
18
|
*/
|
|
26
19
|
export declare function assertDevDatabase(connectionString: string | undefined, { nodeEnv, allowRemote, envFile, productionHost }: DatabaseTargetOptions): void;
|
package/dist/db/target.js
CHANGED
|
@@ -21,9 +21,7 @@ function hostOf(connectionString) {
|
|
|
21
21
|
}
|
|
22
22
|
}
|
|
23
23
|
/**
|
|
24
|
-
* A Neon endpoint's identity, the same for its pooled and direct hosts:
|
|
25
|
-
* `ep-x-123-pooler.us-east-2.aws.neon.tech` and `ep-x-123.us-east-2.aws.neon.tech` are one database.
|
|
26
|
-
* Accepts a bare host or a whole connection string.
|
|
24
|
+
* A Neon endpoint's identity, the same for its pooled and direct hosts: `ep-x-123-pooler.us-east-2.aws.neon.tech` and `ep-x-123.us-east-2.aws.neon.tech` are one database. Accepts a bare host or a whole connection string.
|
|
27
25
|
*/
|
|
28
26
|
export function endpointOf(hostOrUrl) {
|
|
29
27
|
let host = hostOrUrl.trim().toLowerCase();
|
|
@@ -39,12 +37,7 @@ export function endpointOf(hostOrUrl) {
|
|
|
39
37
|
return [first.replace(/-pooler$/, ""), ...rest].join(".");
|
|
40
38
|
}
|
|
41
39
|
/**
|
|
42
|
-
* Local tooling (dev server, scripts, drizzle-kit, psql) works against a Neon dev branch, and must
|
|
43
|
-
* not reach production by accident — a dev branch's URL and production's differ only in the
|
|
44
|
-
* endpoint. So a remote database is allowed only when `PRODUCTION_DATABASE_HOST` names production
|
|
45
|
-
* and this URL is a different endpoint. Production itself is exempt, a loopback database (the tests'
|
|
46
|
-
* PGlite) always passes, and a command that opted in with `ENV_FILE=…` or `ALLOW_REMOTE_DATABASE=1`
|
|
47
|
-
* is deliberate. Throws; the message names the host only, never the credentials.
|
|
40
|
+
* 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.
|
|
48
41
|
*/
|
|
49
42
|
export function assertDevDatabase(connectionString, { nodeEnv, allowRemote, envFile, productionHost }) {
|
|
50
43
|
if (nodeEnv === "production")
|
|
@@ -1,16 +1,12 @@
|
|
|
1
1
|
import type { NodePgDatabase } from "drizzle-orm/node-postgres";
|
|
2
2
|
/**
|
|
3
|
-
* A throwaway Postgres per test file, migrated from the app's committed migrations with the
|
|
4
|
-
* programmatic migrator.
|
|
3
|
+
* A throwaway Postgres per test file, migrated from the app's committed migrations with the programmatic migrator.
|
|
5
4
|
*
|
|
6
5
|
* Two engines, one helper:
|
|
7
6
|
* - default: an in-memory PGlite served over the wire protocol (no Docker, no image pull);
|
|
8
|
-
* - `TEST_DATABASE_URL` set (a CI job with real Postgres): a fresh `t_<hex>` database on that
|
|
9
|
-
* server, dropped on `stop()`.
|
|
7
|
+
* - `TEST_DATABASE_URL` set (a CI job with real Postgres): a fresh `t_<hex>` database on that server, dropped on `stop()`.
|
|
10
8
|
*
|
|
11
|
-
* **Never the development database.** Either way the test gets its own database, so a run cannot
|
|
12
|
-
* see, change or truncate what `pnpm dev` is pointed at — and `url` is exposed so a test can
|
|
13
|
-
* assert exactly that. PGlite allows one connection: a test must not open a second pool on `url`.
|
|
9
|
+
* **Never the development database.** Either way the test gets its own database, so a run cannot see, change or truncate what `pnpm dev` is pointed at — and `url` is exposed so a test can assert exactly that. PGlite allows one connection: a test must not open a second pool on `url`.
|
|
14
10
|
*/
|
|
15
11
|
export type TestDatabase<S extends Record<string, unknown>> = {
|
|
16
12
|
db: NodePgDatabase<S>;
|
package/dist/db/testing/index.js
CHANGED
|
@@ -37,16 +37,12 @@ async function startPglite() {
|
|
|
37
37
|
export async function startTestDatabase(opts) {
|
|
38
38
|
const adminUrl = opts.adminUrl ?? testDatabaseUrl();
|
|
39
39
|
const backend = adminUrl ? await startRealPostgres(adminUrl) : await startPglite();
|
|
40
|
-
// The same client path apps use. On real Postgres the pool is Neon-sized (`max` 5); PGlite gets
|
|
41
|
-
// the retrying single-connection pool.
|
|
40
|
+
// The same client path apps use. On real Postgres the pool is Neon-sized (`max` 5); PGlite gets the retrying single-connection pool.
|
|
42
41
|
const { db, pool } = createDb({ url: backend.url, schema: opts.schema, pglite: backend.pglite });
|
|
43
|
-
// An idle client's socket can die between tests — PGlite drops it after a SQL error, and on real
|
|
44
|
-
// Postgres `drop database … with (force)` terminates it (57P01) while `stop()` is ending the pool.
|
|
45
|
-
// The pool retires the client either way; the next query reports anything real.
|
|
42
|
+
// An idle client's socket can die between tests — PGlite drops it after a SQL error, and on real Postgres `drop database … with (force)` terminates it (57P01) while `stop()` is ending the pool. The pool retires the client either way; the next query reports anything real.
|
|
46
43
|
pool.on("error", () => { });
|
|
47
44
|
try {
|
|
48
|
-
// The committed SQL migrations are the schema's history; the harness applies the same ones
|
|
49
|
-
// production does rather than a parallel definition that could drift.
|
|
45
|
+
// The committed SQL migrations are the schema's history; the harness applies the same ones production does rather than a parallel definition that could drift.
|
|
50
46
|
await migrate(db, { migrationsFolder: opts.migrationsFolder });
|
|
51
47
|
}
|
|
52
48
|
catch (error) {
|
|
@@ -1,4 +1,3 @@
|
|
|
1
|
-
// A side-effect module for a Vitest `setupFiles` entry: it must run before anything that loads
|
|
2
|
-
// `.env`, so it imports only the one function it runs. See `isolateTestEnv`.
|
|
1
|
+
// A side-effect module for a Vitest `setupFiles` entry: it must run before anything that loads `.env`, so it imports only the one function it runs. See `isolateTestEnv`.
|
|
3
2
|
import { isolateTestEnv } from "../../env/testing.js";
|
|
4
3
|
isolateTestEnv();
|
|
@@ -1,11 +1,7 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* PGlite served over the Postgres wire protocol, so the app's `pg` pool talks to it like any other
|
|
3
|
-
* Postgres. Used by the test helper and a template's dev server.
|
|
2
|
+
* PGlite served over the Postgres wire protocol, so the app's `pg` pool talks to it like any other Postgres. Used by the test helper and a template's dev server.
|
|
4
3
|
*
|
|
5
|
-
* `1` because pglite-socket serialises every connection onto PGlite's single session: with more,
|
|
6
|
-
* one connection's open transaction blocks the others and there is no per-connection isolation.
|
|
7
|
-
* At the limit a second connection is refused outright, so a pool pointed at this server must use
|
|
8
|
-
* `max: PGLITE_MAX_CONNECTIONS` and nothing may open another pool against it.
|
|
4
|
+
* `1` because pglite-socket serialises every connection onto PGlite's single session: with more, one connection's open transaction blocks the others and there is no per-connection isolation. At the limit a second connection is refused outright, so a pool pointed at this server must use `max: PGLITE_MAX_CONNECTIONS` and nothing may open another pool against it.
|
|
9
5
|
*/
|
|
10
6
|
export declare const PGLITE_MAX_CONNECTIONS = 1;
|
|
11
7
|
export type PgliteServer = {
|
|
@@ -2,13 +2,9 @@ import { createRequire } from "node:module";
|
|
|
2
2
|
import { createServer } from "node:net";
|
|
3
3
|
import { join } from "node:path";
|
|
4
4
|
/**
|
|
5
|
-
* PGlite served over the Postgres wire protocol, so the app's `pg` pool talks to it like any other
|
|
6
|
-
* Postgres. Used by the test helper and a template's dev server.
|
|
5
|
+
* PGlite served over the Postgres wire protocol, so the app's `pg` pool talks to it like any other Postgres. Used by the test helper and a template's dev server.
|
|
7
6
|
*
|
|
8
|
-
* `1` because pglite-socket serialises every connection onto PGlite's single session: with more,
|
|
9
|
-
* one connection's open transaction blocks the others and there is no per-connection isolation.
|
|
10
|
-
* At the limit a second connection is refused outright, so a pool pointed at this server must use
|
|
11
|
-
* `max: PGLITE_MAX_CONNECTIONS` and nothing may open another pool against it.
|
|
7
|
+
* `1` because pglite-socket serialises every connection onto PGlite's single session: with more, one connection's open transaction blocks the others and there is no per-connection isolation. At the limit a second connection is refused outright, so a pool pointed at this server must use `max: PGLITE_MAX_CONNECTIONS` and nothing may open another pool against it.
|
|
12
8
|
*/
|
|
13
9
|
export const PGLITE_MAX_CONNECTIONS = 1;
|
|
14
10
|
async function freePort(host) {
|
package/dist/env/define-env.d.ts
CHANGED
|
@@ -5,9 +5,7 @@ export interface EnvProblem {
|
|
|
5
5
|
problem: string;
|
|
6
6
|
}
|
|
7
7
|
/**
|
|
8
|
-
* Thrown by `defineEnv` with every problem found, not just the first. The message names each bad
|
|
9
|
-
* variable and says what is wrong with it; it never contains a variable's value, because values
|
|
10
|
-
* can be secrets.
|
|
8
|
+
* 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.
|
|
11
9
|
*/
|
|
12
10
|
export declare class ConfigError extends Error {
|
|
13
11
|
readonly problems: EnvProblem[];
|
|
@@ -24,12 +22,8 @@ export interface EnvSpec<S extends z.ZodRawShape> {
|
|
|
24
22
|
* Validates `source` (default `process.env`, the only place the package reads it) against `schema`.
|
|
25
23
|
*
|
|
26
24
|
* - Blank values are absent; `<NAME>_FILE` is read when `<NAME>` is unset (both set is an error).
|
|
27
|
-
* - Production requirements are checked against the resolved value before defaults apply, so a
|
|
28
|
-
*
|
|
29
|
-
* - During a Next build (`NEXT_PHASE=phase-production-build`) or with `SKIP_ENV_VALIDATION=1`, a
|
|
30
|
-
* build is not a boot: production requirements, groups and a missing `DATABASE_URL` are not
|
|
31
|
-
* enforced (a placeholder stands in), but defaults still apply. With `NODE_ENV=production`,
|
|
32
|
-
* `SKIP_ENV_VALIDATION` is ignored outside the build phase.
|
|
25
|
+
* - 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, groups and a missing `DATABASE_URL` are not enforced (a placeholder stands in), but defaults still apply. With `NODE_ENV=production`, `SKIP_ENV_VALIDATION` is ignored outside the build phase.
|
|
33
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, so apps that extend the stack schema get it for free.
|
|
34
28
|
* - Throws one `ConfigError` listing every problem.
|
|
35
29
|
*/
|
package/dist/env/define-env.js
CHANGED
|
@@ -1,9 +1,7 @@
|
|
|
1
1
|
import { readFileSync } from "node:fs";
|
|
2
2
|
import { z } from "zod";
|
|
3
3
|
/**
|
|
4
|
-
* Thrown by `defineEnv` with every problem found, not just the first. The message names each bad
|
|
5
|
-
* variable and says what is wrong with it; it never contains a variable's value, because values
|
|
6
|
-
* can be secrets.
|
|
4
|
+
* 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.
|
|
7
5
|
*/
|
|
8
6
|
export class ConfigError extends Error {
|
|
9
7
|
problems;
|
|
@@ -20,8 +18,7 @@ const BUILD_PLACEHOLDER_DATABASE_URL = "postgres://unused:unused@127.0.0.1:1/unu
|
|
|
20
18
|
const TRAILING_NEWLINES = /[\r\n]+$/;
|
|
21
19
|
const isBlank = (value) => value === undefined || value.trim() === "";
|
|
22
20
|
/**
|
|
23
|
-
* Resolves one variable: the plain name, else the contents of `<NAME>_FILE`. Blank counts as
|
|
24
|
-
* absent, because `KEY=` in a `.env` file means "not set". Both set is a mistake.
|
|
21
|
+
* Resolves one variable: the plain name, else the contents of `<NAME>_FILE`. Blank counts as absent, because `KEY=` in a `.env` file means "not set". Both set is a mistake.
|
|
25
22
|
*/
|
|
26
23
|
function resolve(name, source, problems) {
|
|
27
24
|
const direct = isBlank(source[name]) ? undefined : source[name];
|
|
@@ -68,12 +65,8 @@ function withVercelAppUrl(source) {
|
|
|
68
65
|
* Validates `source` (default `process.env`, the only place the package reads it) against `schema`.
|
|
69
66
|
*
|
|
70
67
|
* - Blank values are absent; `<NAME>_FILE` is read when `<NAME>` is unset (both set is an error).
|
|
71
|
-
* - Production requirements are checked against the resolved value before defaults apply, so a
|
|
72
|
-
*
|
|
73
|
-
* - During a Next build (`NEXT_PHASE=phase-production-build`) or with `SKIP_ENV_VALIDATION=1`, a
|
|
74
|
-
* build is not a boot: production requirements, groups and a missing `DATABASE_URL` are not
|
|
75
|
-
* enforced (a placeholder stands in), but defaults still apply. With `NODE_ENV=production`,
|
|
76
|
-
* `SKIP_ENV_VALIDATION` is ignored outside the build phase.
|
|
68
|
+
* - 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, groups and a missing `DATABASE_URL` are not enforced (a placeholder stands in), but defaults still apply. With `NODE_ENV=production`, `SKIP_ENV_VALIDATION` is ignored outside the build phase.
|
|
77
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, so apps that extend the stack schema get it for free.
|
|
78
71
|
* - Throws one `ConfigError` listing every problem.
|
|
79
72
|
*/
|
|
@@ -84,17 +77,14 @@ export function defineEnv(spec, rawSource = process.env) {
|
|
|
84
77
|
for (const name of Object.keys(spec.schema)) {
|
|
85
78
|
resolved[name] = resolve(name, source, problems);
|
|
86
79
|
}
|
|
87
|
-
// SKIP_ENV_VALIDATION is for builds and tooling. A production server that inherited it would
|
|
88
|
-
// boot on development defaults (a public BETTER_AUTH_SECRET), so production honours it only in
|
|
89
|
-
// the build phase.
|
|
80
|
+
// SKIP_ENV_VALIDATION is for builds and tooling. A production server that inherited it would boot on development defaults (a public BETTER_AUTH_SECRET), so production honours it only in the build phase.
|
|
90
81
|
const building = source.NEXT_PHASE === "phase-production-build";
|
|
91
82
|
const skipValidation = building || (source.SKIP_ENV_VALIDATION === "1" && source.NODE_ENV !== "production");
|
|
92
83
|
if (skipValidation && "DATABASE_URL" in spec.schema) {
|
|
93
84
|
resolved.DATABASE_URL ??= BUILD_PLACEHOLDER_DATABASE_URL;
|
|
94
85
|
}
|
|
95
86
|
const parsed = z.object(spec.schema).safeParse(resolved);
|
|
96
|
-
// One problem per variable: a bad `_FILE` also leaves its plain name unset, and a missing
|
|
97
|
-
// production secret may also fail the schema.
|
|
87
|
+
// One problem per variable: a bad `_FILE` also leaves its plain name unset, and a missing production secret may also fail the schema.
|
|
98
88
|
const reported = new Set(problems.flatMap((p) => [p.variable, p.variable.replace(/_FILE$/, "")]));
|
|
99
89
|
if (!parsed.success) {
|
|
100
90
|
for (const issue of parsed.error.issues) {
|
|
@@ -1,15 +1,10 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* Zero-dependency `.env` loader for every entry point Next.js does not boot (drizzle config,
|
|
3
|
-
* test setup, scripts). Rules:
|
|
2
|
+
* Zero-dependency `.env` loader for every entry point Next.js does not boot (drizzle config, test setup, scripts). Rules:
|
|
4
3
|
*
|
|
5
|
-
* - never overrides a variable that is already set: real process env always wins, which is what
|
|
6
|
-
*
|
|
7
|
-
* - never throws when the file is absent, since production supplies real env vars. A file named
|
|
8
|
-
* with `ENV_FILE` is different: the command asked for that file, so a missing one throws rather
|
|
9
|
-
* than surfacing later as some unrelated variable being unset;
|
|
4
|
+
* - never overrides a variable that is already set: real process env always wins, which is what makes this safe on Vercel and in CI;
|
|
5
|
+
* - never throws when the file is absent, since production supplies real env vars. A file named with `ENV_FILE` is different: the command asked for that file, so a missing one throws rather than surfacing later as some unrelated variable being unset;
|
|
10
6
|
* - no interpolation, no `export` keyword handling. Keep `.env` boring.
|
|
11
7
|
*
|
|
12
|
-
* With no `path`, the file is `target.ENV_FILE` if set, else `.env`. A `path` passed explicitly
|
|
13
|
-
* that does not exist is skipped silently; only `ENV_FILE` is treated as an explicit request.
|
|
8
|
+
* With no `path`, the file is `target.ENV_FILE` if set, else `.env`. A `path` passed explicitly that does not exist is skipped silently; only `ENV_FILE` is treated as an explicit request.
|
|
14
9
|
*/
|
|
15
10
|
export declare function loadEnvFile(path?: string, target?: Record<string, string | undefined>): void;
|
|
@@ -1,17 +1,12 @@
|
|
|
1
1
|
import { readFileSync } from "node:fs";
|
|
2
2
|
/**
|
|
3
|
-
* Zero-dependency `.env` loader for every entry point Next.js does not boot (drizzle config,
|
|
4
|
-
* test setup, scripts). Rules:
|
|
3
|
+
* Zero-dependency `.env` loader for every entry point Next.js does not boot (drizzle config, test setup, scripts). Rules:
|
|
5
4
|
*
|
|
6
|
-
* - never overrides a variable that is already set: real process env always wins, which is what
|
|
7
|
-
*
|
|
8
|
-
* - never throws when the file is absent, since production supplies real env vars. A file named
|
|
9
|
-
* with `ENV_FILE` is different: the command asked for that file, so a missing one throws rather
|
|
10
|
-
* than surfacing later as some unrelated variable being unset;
|
|
5
|
+
* - never overrides a variable that is already set: real process env always wins, which is what makes this safe on Vercel and in CI;
|
|
6
|
+
* - never throws when the file is absent, since production supplies real env vars. A file named with `ENV_FILE` is different: the command asked for that file, so a missing one throws rather than surfacing later as some unrelated variable being unset;
|
|
11
7
|
* - no interpolation, no `export` keyword handling. Keep `.env` boring.
|
|
12
8
|
*
|
|
13
|
-
* With no `path`, the file is `target.ENV_FILE` if set, else `.env`. A `path` passed explicitly
|
|
14
|
-
* that does not exist is skipped silently; only `ENV_FILE` is treated as an explicit request.
|
|
9
|
+
* With no `path`, the file is `target.ENV_FILE` if set, else `.env`. A `path` passed explicitly that does not exist is skipped silently; only `ENV_FILE` is treated as an explicit request.
|
|
15
10
|
*/
|
|
16
11
|
export function loadEnvFile(path, target = process.env) {
|
|
17
12
|
const envFile = target.ENV_FILE?.trim() ? target.ENV_FILE : undefined;
|
|
@@ -23,8 +18,7 @@ export function loadEnvFile(path, target = process.env) {
|
|
|
23
18
|
contents = readFileSync(/* turbopackIgnore: true */ file, "utf8");
|
|
24
19
|
}
|
|
25
20
|
catch (error) {
|
|
26
|
-
// Only "not there" is expected (production and CI have no .env); EACCES, EISDIR and the like
|
|
27
|
-
// are real problems and must not look like an absent file.
|
|
21
|
+
// Only "not there" is expected (production and CI have no .env); EACCES, EISDIR and the like are real problems and must not look like an absent file.
|
|
28
22
|
if (error.code !== "ENOENT")
|
|
29
23
|
throw error;
|
|
30
24
|
if (named !== undefined) {
|
package/dist/env/stack-env.d.ts
CHANGED
|
@@ -1,9 +1,7 @@
|
|
|
1
1
|
import { z } from "zod";
|
|
2
2
|
import { type EnvSource } from "./define-env.ts";
|
|
3
3
|
/**
|
|
4
|
-
* The variables every stack app shares. Apps extend it:
|
|
5
|
-
* `defineEnv({ schema: { ...stackEnvSchema, MY_VAR: z.string() }, ... })`.
|
|
6
|
-
* Blank values are treated as absent by `defineEnv`, so no field needs its own preprocessing.
|
|
4
|
+
* The variables every stack app shares. Apps extend it: `defineEnv({ schema: { ...stackEnvSchema, MY_VAR: z.string() }, ... })`. Blank values are treated as absent by `defineEnv`, so no field needs its own preprocessing.
|
|
7
5
|
*/
|
|
8
6
|
export declare const stackEnvSchema: {
|
|
9
7
|
NODE_ENV: z.ZodDefault<z.ZodEnum<{
|
package/dist/env/stack-env.js
CHANGED
|
@@ -2,13 +2,10 @@ import { z } from "zod";
|
|
|
2
2
|
import { defineEnv } from "./define-env.js";
|
|
3
3
|
const count = (fallback) => z.coerce.number().int().positive().default(fallback);
|
|
4
4
|
/**
|
|
5
|
-
* The variables every stack app shares. Apps extend it:
|
|
6
|
-
* `defineEnv({ schema: { ...stackEnvSchema, MY_VAR: z.string() }, ... })`.
|
|
7
|
-
* Blank values are treated as absent by `defineEnv`, so no field needs its own preprocessing.
|
|
5
|
+
* The variables every stack app shares. Apps extend it: `defineEnv({ schema: { ...stackEnvSchema, MY_VAR: z.string() }, ... })`. Blank values are treated as absent by `defineEnv`, so no field needs its own preprocessing.
|
|
8
6
|
*/
|
|
9
7
|
export const stackEnvSchema = {
|
|
10
|
-
// Set by tooling, never by `.env`: next dev/build set it, Vitest sets `test`, Vercel's runtime
|
|
11
|
-
// sets `production`.
|
|
8
|
+
// Set by tooling, never by `.env`: next dev/build set it, Vitest sets `test`, Vercel's runtime sets `production`.
|
|
12
9
|
NODE_ENV: z.enum(["development", "test", "production"]).default("development"),
|
|
13
10
|
APP_URL: z.string().default("http://localhost:3000"),
|
|
14
11
|
DATABASE_URL: z.string().min(1),
|
|
@@ -22,8 +19,7 @@ export const stackEnvSchema = {
|
|
|
22
19
|
EMAIL_FROM: z.string().default("App <no-reply@example.invalid>"),
|
|
23
20
|
MAGIC_LINK_SINK_PATH: z.string().default(".magic-links.log"),
|
|
24
21
|
CRON_SECRET: z.string().optional(),
|
|
25
|
-
// Encrypts connected-account tokens (`@wwchen/stack/connections`): 32 bytes, base64
|
|
26
|
-
// (`openssl rand -base64 32`). Keep it forever: a new key makes every stored token unreadable.
|
|
22
|
+
// Encrypts connected-account tokens (`@wwchen/stack/connections`): 32 bytes, base64 (`openssl rand -base64 32`). Keep it forever: a new key makes every stored token unreadable.
|
|
27
23
|
TOKEN_ENCRYPTION_KEY: z
|
|
28
24
|
.string()
|
|
29
25
|
.refine((v) => Buffer.from(v, "base64").length === 32, {
|
package/dist/env/testing.d.ts
CHANGED
|
@@ -1,8 +1,6 @@
|
|
|
1
1
|
/** `TEST_DATABASE_URL`: a real Postgres server for test databases (a CI job's service); else PGlite. */
|
|
2
2
|
export declare function testDatabaseUrl(source?: Record<string, string | undefined>): string | undefined;
|
|
3
3
|
/**
|
|
4
|
-
* Points DATABASE_URL at a closed port before anything loads `.env`: an env loader never overrides
|
|
5
|
-
* a variable that is already set, so `.env`, which may name a real, remote database, cannot reach a
|
|
6
|
-
* test. A test that needs a database starts its own.
|
|
4
|
+
* Points DATABASE_URL at a closed port before anything loads `.env`: an env loader never overrides a variable that is already set, so `.env`, which may name a real, remote database, cannot reach a test. A test that needs a database starts its own.
|
|
7
5
|
*/
|
|
8
6
|
export declare function isolateTestEnv(target?: Record<string, string | undefined>): void;
|
package/dist/env/testing.js
CHANGED
|
@@ -1,14 +1,11 @@
|
|
|
1
|
-
// The environment the test helpers (`@wwchen/stack/db/testing`) read and write, kept here so that
|
|
2
|
-
// src/env/ stays the one place in the package that touches `process.env`.
|
|
1
|
+
// The environment the test helpers (`@wwchen/stack/db/testing`) read and write, kept here so that src/env/ stays the one place in the package that touches `process.env`.
|
|
3
2
|
/** `TEST_DATABASE_URL`: a real Postgres server for test databases (a CI job's service); else PGlite. */
|
|
4
3
|
export function testDatabaseUrl(source = process.env) {
|
|
5
4
|
const url = source.TEST_DATABASE_URL?.trim();
|
|
6
5
|
return url ? url : undefined;
|
|
7
6
|
}
|
|
8
7
|
/**
|
|
9
|
-
* Points DATABASE_URL at a closed port before anything loads `.env`: an env loader never overrides
|
|
10
|
-
* a variable that is already set, so `.env`, which may name a real, remote database, cannot reach a
|
|
11
|
-
* test. A test that needs a database starts its own.
|
|
8
|
+
* Points DATABASE_URL at a closed port before anything loads `.env`: an env loader never overrides a variable that is already set, so `.env`, which may name a real, remote database, cannot reach a test. A test that needs a database starts its own.
|
|
12
9
|
*/
|
|
13
10
|
export function isolateTestEnv(target = process.env) {
|
|
14
11
|
target.DATABASE_URL = "postgres://unused:unused@127.0.0.1:1/unused";
|
package/dist/http/guards.d.ts
CHANGED
|
@@ -3,21 +3,14 @@ export declare function isMutation(request: Request): boolean;
|
|
|
3
3
|
/** `application/json`, with or without parameters (`; charset=utf-8`). */
|
|
4
4
|
export declare function isJsonRequest(request: Request): boolean;
|
|
5
5
|
/**
|
|
6
|
-
* A request that carries no body: no `Content-Type`, and no `Content-Length` (or `0`) and no chunked
|
|
7
|
-
* transfer. `fetch(url, { method: "DELETE" })` sends exactly that. A browser form always sends a
|
|
8
|
-
* `Content-Type`, so a body-less request can never be a cross-site form post.
|
|
6
|
+
* A request that carries no body: no `Content-Type`, and no `Content-Length` (or `0`) and no chunked transfer. `fetch(url, { method: "DELETE" })` sends exactly that. A browser form always sends a `Content-Type`, so a body-less request can never be a cross-site form post.
|
|
9
7
|
*/
|
|
10
8
|
export declare function hasNoBody(request: Request): boolean;
|
|
11
9
|
/**
|
|
12
|
-
* Whether a mutation came from this app's own pages. Browsers attach `Origin` to every cross-origin
|
|
13
|
-
* and every non-GET request, so it is compared with the host the request was addressed to (the
|
|
14
|
-
* host, not the scheme: a proxy that ends TLS makes the scheme the app sees untrue). Without
|
|
15
|
-
* `Origin`, `Sec-Fetch-Site` decides. A request with neither is not from a browser page, and a
|
|
16
|
-
* session cookie must not ride on it, so it is refused.
|
|
10
|
+
* Whether a mutation came from this app's own pages. Browsers attach `Origin` to every cross-origin and every non-GET request, so it is compared with the host the request was addressed to (the host, not the scheme: a proxy that ends TLS makes the scheme the app sees untrue). Without `Origin`, `Sec-Fetch-Site` decides. A request with neither is not from a browser page, and a session cookie must not ride on it, so it is refused.
|
|
17
11
|
*/
|
|
18
12
|
export declare function isSameOrigin(request: Request): boolean;
|
|
19
13
|
/**
|
|
20
|
-
* Whether `Authorization` is `Bearer <secret>`. An unset or empty secret matches nothing, so
|
|
21
|
-
* `Bearer undefined` is never accepted. The comparison is constant-time.
|
|
14
|
+
* Whether `Authorization` is `Bearer <secret>`. An unset or empty secret matches nothing, so `Bearer undefined` is never accepted. The comparison is constant-time.
|
|
22
15
|
*/
|
|
23
16
|
export declare function bearerMatches(request: Request, secret: string | undefined): boolean;
|
package/dist/http/guards.js
CHANGED
|
@@ -1,7 +1,6 @@
|
|
|
1
1
|
import { timingSafeEqual } from "node:crypto";
|
|
2
2
|
/**
|
|
3
|
-
* Request guards shared by the API wrapper, the cron route and the health route. Pure functions of
|
|
4
|
-
* a `Request`: none reads the environment or the database.
|
|
3
|
+
* Request guards shared by the API wrapper, the cron route and the health route. Pure functions of a `Request`: none reads the environment or the database.
|
|
5
4
|
*/
|
|
6
5
|
const SAFE_METHODS = new Set(["GET", "HEAD", "OPTIONS"]);
|
|
7
6
|
/** A method that can change state: everything but GET, HEAD and OPTIONS. */
|
|
@@ -14,9 +13,7 @@ export function isJsonRequest(request) {
|
|
|
14
13
|
return type === "application/json";
|
|
15
14
|
}
|
|
16
15
|
/**
|
|
17
|
-
* A request that carries no body: no `Content-Type`, and no `Content-Length` (or `0`) and no chunked
|
|
18
|
-
* transfer. `fetch(url, { method: "DELETE" })` sends exactly that. A browser form always sends a
|
|
19
|
-
* `Content-Type`, so a body-less request can never be a cross-site form post.
|
|
16
|
+
* A request that carries no body: no `Content-Type`, and no `Content-Length` (or `0`) and no chunked transfer. `fetch(url, { method: "DELETE" })` sends exactly that. A browser form always sends a `Content-Type`, so a body-less request can never be a cross-site form post.
|
|
20
17
|
*/
|
|
21
18
|
export function hasNoBody(request) {
|
|
22
19
|
if (request.headers.get("content-type") !== null)
|
|
@@ -42,11 +39,7 @@ function servedHost(request) {
|
|
|
42
39
|
return forwarded || request.headers.get("host") || new URL(request.url).host;
|
|
43
40
|
}
|
|
44
41
|
/**
|
|
45
|
-
* Whether a mutation came from this app's own pages. Browsers attach `Origin` to every cross-origin
|
|
46
|
-
* and every non-GET request, so it is compared with the host the request was addressed to (the
|
|
47
|
-
* host, not the scheme: a proxy that ends TLS makes the scheme the app sees untrue). Without
|
|
48
|
-
* `Origin`, `Sec-Fetch-Site` decides. A request with neither is not from a browser page, and a
|
|
49
|
-
* session cookie must not ride on it, so it is refused.
|
|
42
|
+
* Whether a mutation came from this app's own pages. Browsers attach `Origin` to every cross-origin and every non-GET request, so it is compared with the host the request was addressed to (the host, not the scheme: a proxy that ends TLS makes the scheme the app sees untrue). Without `Origin`, `Sec-Fetch-Site` decides. A request with neither is not from a browser page, and a session cookie must not ride on it, so it is refused.
|
|
50
43
|
*/
|
|
51
44
|
export function isSameOrigin(request) {
|
|
52
45
|
const origin = request.headers.get("origin");
|
|
@@ -55,8 +48,7 @@ export function isSameOrigin(request) {
|
|
|
55
48
|
return request.headers.get("sec-fetch-site") === "same-origin";
|
|
56
49
|
}
|
|
57
50
|
/**
|
|
58
|
-
* Whether `Authorization` is `Bearer <secret>`. An unset or empty secret matches nothing, so
|
|
59
|
-
* `Bearer undefined` is never accepted. The comparison is constant-time.
|
|
51
|
+
* Whether `Authorization` is `Bearer <secret>`. An unset or empty secret matches nothing, so `Bearer undefined` is never accepted. The comparison is constant-time.
|
|
60
52
|
*/
|
|
61
53
|
export function bearerMatches(request, secret) {
|
|
62
54
|
if (!secret)
|
package/dist/jobs/index.d.ts
CHANGED
|
@@ -1,12 +1,7 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* Helpers for scheduled jobs that work for many people (one run does the work for everyone).
|
|
3
3
|
*
|
|
4
|
-
* **Alert on new failures only.** An uptime monitor that calls the job alerts when it answers 500.
|
|
5
|
-
* If every failure answered 500, one person whose runs keep failing would hold the monitor down for
|
|
6
|
-
* good, and the next person to break would raise no alert. So a failure counts as *new* for its
|
|
7
|
-
* first `ALERT_FOR_HOURS` (24h) and the job answers 500 only while someone's failure is new
|
|
8
|
-
* (`cronRoute` does that when the job returns `alerting: true`). The person stays marked failing in
|
|
9
|
-
* the app until fixed; the monitor recovers and is free to alert on the next streak.
|
|
4
|
+
* **Alert on new failures only.** An uptime monitor that calls the job alerts when it answers 500. If every failure answered 500, one person whose runs keep failing would hold the monitor down for good, and the next person to break would raise no alert. So a failure counts as *new* for its first `ALERT_FOR_HOURS` (24h) and the job answers 500 only while someone's failure is new (`cronRoute` does that when the job returns `alerting: true`). The person stays marked failing in the app until fixed; the monitor recovers and is free to alert on the next streak.
|
|
10
5
|
*/
|
|
11
6
|
export declare const ALERT_FOR_HOURS = 24;
|
|
12
7
|
type Timestamp = string | Date;
|
|
@@ -17,9 +12,7 @@ export type RunOutcome = {
|
|
|
17
12
|
failingSince?: Timestamp | null;
|
|
18
13
|
};
|
|
19
14
|
/**
|
|
20
|
-
* When `run`'s failure streak began: the previous run's streak start when that one failed too,
|
|
21
|
-
* otherwise `run` itself. Null for a successful run. `previous` is the person's run before this
|
|
22
|
-
* one.
|
|
15
|
+
* When `run`'s failure streak began: the previous run's streak start when that one failed too, otherwise `run` itself. Null for a successful run. `previous` is the person's run before this one.
|
|
23
16
|
*/
|
|
24
17
|
export declare function failingSince(run: {
|
|
25
18
|
ok: boolean;
|
package/dist/jobs/index.js
CHANGED
|
@@ -1,20 +1,13 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* Helpers for scheduled jobs that work for many people (one run does the work for everyone).
|
|
3
3
|
*
|
|
4
|
-
* **Alert on new failures only.** An uptime monitor that calls the job alerts when it answers 500.
|
|
5
|
-
* If every failure answered 500, one person whose runs keep failing would hold the monitor down for
|
|
6
|
-
* good, and the next person to break would raise no alert. So a failure counts as *new* for its
|
|
7
|
-
* first `ALERT_FOR_HOURS` (24h) and the job answers 500 only while someone's failure is new
|
|
8
|
-
* (`cronRoute` does that when the job returns `alerting: true`). The person stays marked failing in
|
|
9
|
-
* the app until fixed; the monitor recovers and is free to alert on the next streak.
|
|
4
|
+
* **Alert on new failures only.** An uptime monitor that calls the job alerts when it answers 500. If every failure answered 500, one person whose runs keep failing would hold the monitor down for good, and the next person to break would raise no alert. So a failure counts as *new* for its first `ALERT_FOR_HOURS` (24h) and the job answers 500 only while someone's failure is new (`cronRoute` does that when the job returns `alerting: true`). The person stays marked failing in the app until fixed; the monitor recovers and is free to alert on the next streak.
|
|
10
5
|
*/
|
|
11
6
|
export const ALERT_FOR_HOURS = 24;
|
|
12
7
|
const ms = (t) => (typeof t === "string" ? Date.parse(t) : t.getTime());
|
|
13
8
|
const iso = (t) => (typeof t === "string" ? t : t.toISOString());
|
|
14
9
|
/**
|
|
15
|
-
* When `run`'s failure streak began: the previous run's streak start when that one failed too,
|
|
16
|
-
* otherwise `run` itself. Null for a successful run. `previous` is the person's run before this
|
|
17
|
-
* one.
|
|
10
|
+
* When `run`'s failure streak began: the previous run's streak start when that one failed too, otherwise `run` itself. Null for a successful run. `previous` is the person's run before this one.
|
|
18
11
|
*/
|
|
19
12
|
export function failingSince(run, previous) {
|
|
20
13
|
if (run.ok)
|