@cubicecho/server-kit 0.0.0-stage → 0.1.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/dist/db/ssl.js ADDED
@@ -0,0 +1,91 @@
1
+ /**
2
+ * Domain suffixes reserved for, or conventionally used on, private networks.
3
+ * `.local` is mDNS, `.home.arpa` is the RFC 8375 name for a home network, and
4
+ * the rest are what routers and Docker hosts are actually called.
5
+ */
6
+ const PRIVATE_SUFFIXES = [
7
+ '.lan',
8
+ '.local',
9
+ '.localdomain',
10
+ '.home',
11
+ '.home.arpa',
12
+ '.internal',
13
+ '.intranet',
14
+ '.private',
15
+ ];
16
+ /**
17
+ * IPv4 blocks that never route off a private network, by first octet and the
18
+ * span of second octets: loopback, the three RFC 1918 ranges, then link-local.
19
+ */
20
+ const PRIVATE_IPV4 = [
21
+ { first: 127, low: 0, high: 255 },
22
+ { first: 10, low: 0, high: 255 },
23
+ { first: 172, low: 16, high: 31 },
24
+ { first: 192, low: 168, high: 168 },
25
+ { first: 169, low: 254, high: 254 },
26
+ ];
27
+ /**
28
+ * The URL's hostname, lowercased and without IPv6 brackets, or null when the URL does not parse.
29
+ *
30
+ * @param url - The connection string.
31
+ * @returns The hostname, or null.
32
+ */
33
+ function hostnameOf(url) {
34
+ try {
35
+ return new URL(url).hostname.replace(/^\[|\]$/g, '').toLowerCase();
36
+ }
37
+ catch {
38
+ return null;
39
+ }
40
+ }
41
+ /**
42
+ * Whether a host is this machine or on a private network.
43
+ *
44
+ * "Private" is wider than loopback, because self-hosting is: a compose service
45
+ * and a box on the LAN are both names nothing outside can reach.
46
+ *
47
+ * @param hostname - The host from a URL, lowercased and without IPv6 brackets.
48
+ * @returns true for localhost, a dotless name, a private-use suffix or a private address.
49
+ */
50
+ export function isPrivateHost(hostname) {
51
+ if (hostname === 'localhost' || hostname.endsWith('.localhost')) {
52
+ return true;
53
+ }
54
+ // A name with no dots is a container or LAN hostname, not a public address.
55
+ if (hostname.includes('.') === false && hostname.includes(':') === false) {
56
+ return true;
57
+ }
58
+ // Nor is a name under a private-use suffix: the router or mDNS resolves it,
59
+ // and the dot in it says nothing about reach.
60
+ if (PRIVATE_SUFFIXES.some((suffix) => hostname.endsWith(suffix))) {
61
+ return true;
62
+ }
63
+ const ipv4 = /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/.exec(hostname);
64
+ if (ipv4) {
65
+ const [firstOctet, secondOctet] = ipv4.slice(1).map(Number);
66
+ return PRIVATE_IPV4.some((range) => range.first === firstOctet && secondOctet >= range.low && secondOctet <= range.high);
67
+ }
68
+ // Loopback, unique-local fc00::/7, then link-local fe80::/10.
69
+ return hostname === '::1' || /^f[cd]/.test(hostname) || /^fe[89ab]/.test(hostname);
70
+ }
71
+ /**
72
+ * Whether to insist on TLS for a connection string.
73
+ *
74
+ * Read from the parsed hostname, never the raw string: a URL carrying
75
+ * credentials puts the userinfo where a prefix match looks for the host. A
76
+ * private host speaks no TLS by default, and demanding it breaks the connection.
77
+ *
78
+ * @param url - The connection string.
79
+ * @returns false for a private host, and when the URL sets its own `sslmode`.
80
+ */
81
+ export function requiresSsl(url) {
82
+ // An explicit sslmode is the operator's decision; postgres-js reads it itself.
83
+ if (/[?&]sslmode=/i.test(url)) {
84
+ return false;
85
+ }
86
+ const hostname = hostnameOf(url);
87
+ if (hostname === null) {
88
+ return false;
89
+ }
90
+ return isPrivateHost(hostname) === false;
91
+ }
@@ -0,0 +1,22 @@
1
+ import type { Queryable } from './wait.ts';
2
+ /** What the app needs of its Postgres. */
3
+ export interface PostgresNeeds {
4
+ /** Extensions the migrations create, by name. */
5
+ extensions?: readonly string[];
6
+ /**
7
+ * The newest major the app is tested on.
8
+ *
9
+ * @defaultValue `TESTED_POSTGRES_MAJOR`
10
+ */
11
+ testedMajor?: number;
12
+ }
13
+ /**
14
+ * Refuses a Postgres the app cannot run on, before anything is migrated.
15
+ *
16
+ * @param db - Drizzle client.
17
+ * @param [needs] - What the app needs besides the minimum version.
18
+ * @param [log] - Called with a warning when the server is newer than the app is tested on.
19
+ * @returns Resolves once the server is known to be good enough.
20
+ * @throws {@link DatabaseBootError} If it is too old, or lacks an extension.
21
+ */
22
+ export declare function requirePostgres(db: Queryable, { extensions, testedMajor }?: PostgresNeeds, log?: (message: string) => void): Promise<void>;
@@ -0,0 +1,57 @@
1
+ import { inArray, sql } from 'drizzle-orm';
2
+ import { MIN_POSTGRES_MAJOR, TESTED_POSTGRES_MAJOR } from '../consts.js';
3
+ import { DatabaseBootError } from './errors.js';
4
+ /** `server_version_num` is the major times this, plus the minor. */
5
+ const VERSION_NUM_PER_MAJOR = 10_000;
6
+ /**
7
+ * Runs a query and reads its rows, whichever driver the client is on.
8
+ *
9
+ * @param db - Drizzle client. postgres-js answers with the rows, pg and PGlite with an object holding them.
10
+ * @param query - The query.
11
+ * @returns The rows.
12
+ */
13
+ async function rowsOf(db, query) {
14
+ const answer = await db.execute(query);
15
+ const isWrapped = typeof answer === 'object' && answer !== null && 'rows' in answer;
16
+ const rows = isWrapped ? answer.rows : answer;
17
+ return Array.isArray(rows) ? rows : [];
18
+ }
19
+ /**
20
+ * Refuses a Postgres the app cannot run on, before anything is migrated.
21
+ *
22
+ * @param db - Drizzle client.
23
+ * @param [needs] - What the app needs besides the minimum version.
24
+ * @param [log] - Called with a warning when the server is newer than the app is tested on.
25
+ * @returns Resolves once the server is known to be good enough.
26
+ * @throws {@link DatabaseBootError} If it is too old, or lacks an extension.
27
+ */
28
+ export async function requirePostgres(db, { extensions = [], testedMajor = TESTED_POSTGRES_MAJOR } = {}, log = console.warn) {
29
+ const [server] = await rowsOf(db, sql `select current_setting('server_version_num')::int as number, current_setting('server_version') as name`);
30
+ const major = Math.floor(Number(server?.number) / VERSION_NUM_PER_MAJOR);
31
+ if (major < MIN_POSTGRES_MAJOR) {
32
+ throw new DatabaseBootError(`Postgres ${server?.name} is too old: ${MIN_POSTGRES_MAJOR} or later is needed. Nothing was changed.`);
33
+ }
34
+ if (major > testedMajor) {
35
+ log(`[db] Postgres ${server?.name} is newer than ${testedMajor}, which this version is tested on`);
36
+ }
37
+ await requireExtensions(db, extensions);
38
+ }
39
+ /**
40
+ * Refuses a server that lacks an extension the migrations create.
41
+ *
42
+ * @param db - Drizzle client.
43
+ * @param extensions - Extension names.
44
+ * @throws {@link DatabaseBootError} Naming the ones the server does not have.
45
+ */
46
+ async function requireExtensions(db, extensions) {
47
+ if (extensions.length === 0) {
48
+ return;
49
+ }
50
+ const isWanted = inArray(sql `name`, [...extensions]);
51
+ const available = await rowsOf(db, sql `select name from pg_available_extensions where ${isWanted}`);
52
+ const names = available.map((extension) => extension.name);
53
+ const missing = extensions.filter((extension) => names.includes(extension) === false);
54
+ if (missing.length > 0) {
55
+ throw new DatabaseBootError(`Postgres has no ${missing.join(', ')} extension installed. Nothing was changed.`);
56
+ }
57
+ }
@@ -0,0 +1,23 @@
1
+ import { type SQL } from 'drizzle-orm';
2
+ import { type DatabaseSettings } from './defaults.ts';
3
+ /** Anything that can run a query: the Drizzle client on postgres-js, pg or PGlite. */
4
+ export interface Queryable {
5
+ execute: (query: SQL) => PromiseLike<unknown>;
6
+ }
7
+ /**
8
+ * Whether a failure is a database that is still starting.
9
+ *
10
+ * @param error - Whatever was thrown.
11
+ * @returns true when waiting may cure it.
12
+ */
13
+ export declare function isStillStarting(error: unknown): boolean;
14
+ /**
15
+ * Waits until Postgres answers a query.
16
+ *
17
+ * @param db - Drizzle client.
18
+ * @param [overrides] - Settings that differ from `DATABASE_DEFAULTS`.
19
+ * @param [log] - Called before each retry.
20
+ * @returns Resolves once connected.
21
+ * @throws A failure that waiting will not cure at once, or the last one when the time is up.
22
+ */
23
+ export declare function waitForDatabase(db: Queryable, overrides?: Partial<DatabaseSettings>, log?: (message: string) => void): Promise<void>;
@@ -0,0 +1,52 @@
1
+ import { setTimeout as sleep } from 'node:timers/promises';
2
+ import { sql } from 'drizzle-orm';
3
+ import { DATABASE_DEFAULTS } from './defaults.js';
4
+ import { errorCode } from './errors.js';
5
+ /** Codes that mean "not up yet". `57P03` is Postgres starting. Anything else is a real failure. */
6
+ const RETRYABLE_CODES = [
7
+ 'ECONNREFUSED',
8
+ 'ECONNRESET',
9
+ 'ENOTFOUND',
10
+ 'EAI_AGAIN',
11
+ 'ETIMEDOUT',
12
+ '57P03',
13
+ ];
14
+ /**
15
+ * Whether a failure is a database that is still starting.
16
+ *
17
+ * @param error - Whatever was thrown.
18
+ * @returns true when waiting may cure it.
19
+ */
20
+ export function isStillStarting(error) {
21
+ const code = errorCode(error);
22
+ return code !== undefined && RETRYABLE_CODES.includes(code);
23
+ }
24
+ /**
25
+ * Waits until Postgres answers a query.
26
+ *
27
+ * @param db - Drizzle client.
28
+ * @param [overrides] - Settings that differ from `DATABASE_DEFAULTS`.
29
+ * @param [log] - Called before each retry.
30
+ * @returns Resolves once connected.
31
+ * @throws A failure that waiting will not cure at once, or the last one when the time is up.
32
+ */
33
+ export async function waitForDatabase(db, overrides = {}, log = console.warn) {
34
+ const settings = { ...DATABASE_DEFAULTS, ...overrides };
35
+ const deadline = Date.now() + settings.connectTimeoutMs;
36
+ const nextDelay = (delay) => Math.min(delay * settings.retryBackoffFactor, settings.maxRetryDelayMs);
37
+ for (let delay = settings.firstRetryDelayMs;; delay = nextDelay(delay)) {
38
+ try {
39
+ await db.execute(sql `select 1`);
40
+ return;
41
+ }
42
+ catch (error) {
43
+ const isOutOfTime = Date.now() + delay > deadline;
44
+ const shouldGiveUp = isStillStarting(error) === false || isOutOfTime;
45
+ if (shouldGiveUp) {
46
+ throw error;
47
+ }
48
+ log(`[db] Postgres is not answering yet (${errorCode(error)}), retrying in ${delay} ms`);
49
+ await sleep(delay);
50
+ }
51
+ }
52
+ }
@@ -0,0 +1,17 @@
1
+ import { type PostgresFiles } from './postgres-problems.ts';
2
+ import { type SchemaExceptions } from './schema-problems.ts';
3
+ export { type PostgresFiles, type PostgresFindings, postgresProblems } from './postgres-problems.ts';
4
+ export { type SchemaExceptions, schemaProblems } from './schema-problems.ts';
5
+ /**
6
+ * Registers the tests that hold a schema to the table conventions: ids, join tables, time zones and foreign-key indexes.
7
+ *
8
+ * @param schema - The module of Drizzle tables.
9
+ * @param [exceptions] - Tables the id rule does not apply to, with the reasons.
10
+ */
11
+ export declare function checkSchemaConventions(schema: Record<string, unknown>, exceptions?: SchemaExceptions): void;
12
+ /**
13
+ * Registers the test that a repo's compose files, CI and tests agree on a Postgres major.
14
+ *
15
+ * @param files - Where the repo names them.
16
+ */
17
+ export declare function checkPostgresVersion(files: PostgresFiles): void;
@@ -0,0 +1,51 @@
1
+ import { PGlite } from '@electric-sql/pglite';
2
+ import { describe, expect, it } from 'vitest';
3
+ import { postgresProblems } from './postgres-problems.js';
4
+ import { schemaProblems } from './schema-problems.js';
5
+ export { postgresProblems } from './postgres-problems.js';
6
+ export { schemaProblems } from './schema-problems.js';
7
+ /**
8
+ * Registers the tests that hold a schema to the table conventions: ids, join tables, time zones and foreign-key indexes.
9
+ *
10
+ * @param schema - The module of Drizzle tables.
11
+ * @param [exceptions] - Tables the id rule does not apply to, with the reasons.
12
+ */
13
+ export function checkSchemaConventions(schema, exceptions = {}) {
14
+ const { tables, exceptions: unneeded } = schemaProblems(schema, exceptions);
15
+ describe('schema conventions', () => {
16
+ it('has tables to check', () => {
17
+ expect(tables.size).toBeGreaterThan(0);
18
+ });
19
+ it.each([...tables])('%s', (_name, problems) => {
20
+ expect(problems).toEqual([]);
21
+ });
22
+ it('needs every exception it lists', () => {
23
+ expect(unneeded).toEqual([]);
24
+ });
25
+ });
26
+ }
27
+ /**
28
+ * Registers the test that a repo's compose files, CI and tests agree on a Postgres major.
29
+ *
30
+ * @param files - Where the repo names them.
31
+ */
32
+ export function checkPostgresVersion(files) {
33
+ it('runs one Postgres major everywhere', async () => {
34
+ const { problems, warnings } = postgresProblems(files, await pgliteMajor());
35
+ for (const warning of warnings) {
36
+ console.warn(`[db] ${warning}`);
37
+ }
38
+ expect(problems).toEqual([]);
39
+ });
40
+ }
41
+ /**
42
+ * Asks the tests' Postgres for its major.
43
+ *
44
+ * @returns PGlite's major.
45
+ */
46
+ async function pgliteMajor() {
47
+ const client = new PGlite('memory://');
48
+ const { rows } = await client.query('show server_version');
49
+ await client.close();
50
+ return Number.parseInt(rows.at(0)?.server_version ?? '', 10);
51
+ }
@@ -0,0 +1,38 @@
1
+ /** Where a repo says which Postgres it runs. */
2
+ export interface PostgresFiles {
3
+ /** The repository's root. */
4
+ root: string;
5
+ /**
6
+ * The compose file that is deployed.
7
+ *
8
+ * @defaultValue `docker-compose.yml`
9
+ */
10
+ deployed?: string;
11
+ /**
12
+ * The compose file development runs.
13
+ *
14
+ * @defaultValue `docker-compose.dev.yml`
15
+ */
16
+ development?: string;
17
+ /**
18
+ * The newest major the app is tested on, as passed to `prepareDatabase`.
19
+ *
20
+ * @defaultValue `TESTED_POSTGRES_MAJOR`
21
+ */
22
+ testedMajor?: number;
23
+ }
24
+ /** What a comparison found. */
25
+ export interface PostgresFindings {
26
+ /** What has to be fixed. */
27
+ problems: string[];
28
+ /** What is allowed, and worth knowing. */
29
+ warnings: string[];
30
+ }
31
+ /**
32
+ * Compares the Postgres majors a repo names with each other and with the one its tests run on.
33
+ *
34
+ * @param files - Where the repo names them.
35
+ * @param tested - The major the tests run on.
36
+ * @returns What disagrees.
37
+ */
38
+ export declare function postgresProblems({ root, deployed, development, testedMajor, }: PostgresFiles, tested: number): PostgresFindings;
@@ -0,0 +1,57 @@
1
+ import { readdirSync, readFileSync } from 'node:fs';
2
+ import { join } from 'node:path';
3
+ import { MIN_POSTGRES_MAJOR, TESTED_POSTGRES_MAJOR } from '../consts.js';
4
+ const WORKFLOWS = '.github/workflows';
5
+ /** A Postgres image and its major: `postgres:18-alpine`, `pgvector/pgvector:pg18`. */
6
+ const POSTGRES_IMAGE = /^\s*image:\s*["']?(?:postgres:|pgvector\/pgvector:pg)(\d+)/gm;
7
+ /**
8
+ * Compares the Postgres majors a repo names with each other and with the one its tests run on.
9
+ *
10
+ * @param files - Where the repo names them.
11
+ * @param tested - The major the tests run on.
12
+ * @returns What disagrees.
13
+ */
14
+ export function postgresProblems({ root, deployed = 'docker-compose.yml', development = 'docker-compose.dev.yml', testedMajor = TESTED_POSTGRES_MAJOR, }, tested) {
15
+ const major = postgresMajors(join(root, deployed)).at(0);
16
+ if (major === undefined) {
17
+ return { problems: [`${deployed} names no Postgres image`], warnings: [] };
18
+ }
19
+ const workflows = readdirSync(join(root, WORKFLOWS)).map((file) => join(root, WORKFLOWS, file));
20
+ const problems = [
21
+ ...(major < MIN_POSTGRES_MAJOR ? [`${deployed} runs ${major}, and ${MIN_POSTGRES_MAJOR} is the minimum`] : []),
22
+ ...(major === testedMajor ? [] : [`${deployed} runs ${major}, and boot says ${testedMajor} is tested`]),
23
+ ...disagreement(deployed, postgresMajors(join(root, deployed)), major),
24
+ ...disagreement(development, postgresMajors(join(root, development)), major),
25
+ ...disagreement('CI', workflows.flatMap(postgresMajors), major),
26
+ ...(tested < major ? [`the tests run on ${tested}, older than the ${major} that is deployed`] : []),
27
+ ];
28
+ const isAhead = tested > major;
29
+ const warnings = isAhead
30
+ ? [`the tests run on Postgres ${tested}, and ${major} is deployed: a newer feature passes here and fails there`]
31
+ : [];
32
+ return { problems, warnings };
33
+ }
34
+ /**
35
+ * Finds the Postgres majors a file's images name.
36
+ *
37
+ * @param file - The file.
38
+ * @returns One major per image.
39
+ */
40
+ function postgresMajors(file) {
41
+ return [...readFileSync(file, 'utf8').matchAll(POSTGRES_IMAGE)].map(([, major]) => Number(major));
42
+ }
43
+ /**
44
+ * Compares one place with what is deployed.
45
+ *
46
+ * @param where - What to call the place.
47
+ * @param majors - The majors it names.
48
+ * @param deployed - The major that is deployed.
49
+ * @returns What is wrong: no Postgres there, or another major.
50
+ */
51
+ function disagreement(where, majors, deployed) {
52
+ if (majors.length === 0) {
53
+ return [`${where} runs no Postgres`];
54
+ }
55
+ const others = [...new Set(majors)].filter((major) => major !== deployed);
56
+ return others.map((major) => `${where} runs ${major}, and ${deployed} is deployed`);
57
+ }
@@ -0,0 +1,18 @@
1
+ /** Tables the id rule does not apply to. Each key is a SQL table name, and each value the reason. */
2
+ export interface SchemaExceptions {
3
+ /** Derived data: written by code or triggers from other tables, never referenced, and not in the GraphQL schema. */
4
+ derived?: Readonly<Record<string, string>>;
5
+ /** Tables that keep a text id from before ids were UUIDv7. A new table is never one. */
6
+ legacyIds?: Readonly<Record<string, string>>;
7
+ }
8
+ /**
9
+ * Finds what breaks the table conventions.
10
+ *
11
+ * @param schema - A module of Drizzle tables. Its other exports are ignored.
12
+ * @param [exceptions] - Tables the id rule does not apply to.
13
+ * @returns Each table's problems by SQL name, empty when it has none, and those of the exceptions under `exceptions`.
14
+ */
15
+ export declare function schemaProblems(schema: Record<string, unknown>, { derived, legacyIds }?: SchemaExceptions): {
16
+ tables: Map<string, string[]>;
17
+ exceptions: string[];
18
+ };
@@ -0,0 +1,153 @@
1
+ import { is, SQL } from 'drizzle-orm';
2
+ import { getTableConfig, PgDialect, PgTable } from 'drizzle-orm/pg-core';
3
+ /** What an id column's default is. */
4
+ const UUID_V7_DEFAULT = 'uuidv7()';
5
+ /** The fewest columns a join table's key can have: one for each end. */
6
+ const JOIN_KEY_COLUMNS = 2;
7
+ const dialect = new PgDialect();
8
+ /**
9
+ * Finds what breaks the table conventions.
10
+ *
11
+ * @param schema - A module of Drizzle tables. Its other exports are ignored.
12
+ * @param [exceptions] - Tables the id rule does not apply to.
13
+ * @returns Each table's problems by SQL name, empty when it has none, and those of the exceptions under `exceptions`.
14
+ */
15
+ export function schemaProblems(schema, { derived = {}, legacyIds = {} } = {}) {
16
+ const configs = Object.values(schema).flatMap((value) => (is(value, PgTable) ? [getTableConfig(value)] : []));
17
+ const excused = new Set([...Object.keys(derived), ...Object.keys(legacyIds)]);
18
+ const tables = new Map(configs.map((config) => {
19
+ const needsId = isJoinTable(config) === false && excused.has(config.name) === false;
20
+ const problems = [...(needsId ? idProblems(config) : []), ...timeZoneProblems(config), ...indexProblems(config)];
21
+ return [config.name, problems];
22
+ }));
23
+ return { tables, exceptions: exceptionProblems(configs, derived, legacyIds) };
24
+ }
25
+ /**
26
+ * Whether a table only links others: its primary key is its foreign keys.
27
+ *
28
+ * @param config - The table.
29
+ * @returns true for a join table.
30
+ */
31
+ function isJoinTable(config) {
32
+ const keyColumns = config.primaryKeys.at(0)?.columns ?? [];
33
+ const references = foreignKeyColumns(config).flat();
34
+ return keyColumns.length >= JOIN_KEY_COLUMNS && keyColumns.every((column) => references.includes(column.name));
35
+ }
36
+ /**
37
+ * Lists the columns of each foreign key.
38
+ *
39
+ * @param config - The table.
40
+ * @returns One list of column names per key.
41
+ */
42
+ function foreignKeyColumns(config) {
43
+ return config.foreignKeys.map((key) => key.reference().columns.map((column) => column.name));
44
+ }
45
+ /**
46
+ * Renders a column's database default.
47
+ *
48
+ * @param column - The column.
49
+ * @returns Its SQL, or undefined when it has none or it is a plain value.
50
+ */
51
+ function defaultSql(column) {
52
+ return is(column.default, SQL) ? dialect.sqlToQuery(column.default).sql : undefined;
53
+ }
54
+ /**
55
+ * Checks a table's id.
56
+ *
57
+ * @param config - A table that needs one.
58
+ * @returns What is wrong with it.
59
+ */
60
+ function idProblems(config) {
61
+ const id = config.columns.find((column) => column.name === 'id');
62
+ if (id === undefined) {
63
+ return ['has no id column'];
64
+ }
65
+ const problems = [];
66
+ if (id.primary === false) {
67
+ problems.push('its id is not the primary key');
68
+ }
69
+ if (id.getSQLType() !== 'uuid') {
70
+ problems.push(`its id is ${id.getSQLType()}, not uuid`);
71
+ }
72
+ if (defaultSql(id) !== UUID_V7_DEFAULT) {
73
+ problems.push(`its id defaults to ${defaultSql(id) ?? 'nothing'}, not ${UUID_V7_DEFAULT}`);
74
+ }
75
+ return problems;
76
+ }
77
+ /**
78
+ * Checks that every timestamp has a time zone.
79
+ *
80
+ * @param config - The table.
81
+ * @returns One problem per column without.
82
+ */
83
+ function timeZoneProblems(config) {
84
+ return config.columns
85
+ .filter((column) => {
86
+ const type = column.getSQLType();
87
+ return type.startsWith('timestamp') && type.endsWith('with time zone') === false;
88
+ })
89
+ .map((column) => `${column.name} has no time zone`);
90
+ }
91
+ /**
92
+ * Lists the columns a lookup can use an index for: those that come first in one.
93
+ *
94
+ * @param config - The table.
95
+ * @returns Column names. A partial index does not count, since it misses rows.
96
+ */
97
+ function leadingColumns(config) {
98
+ const wholeIndexes = config.indexes.filter((index) => index.config.where === undefined);
99
+ return new Set([
100
+ ...wholeIndexes.map((index) => {
101
+ const [first] = index.config.columns;
102
+ // An index on an expression has no column name.
103
+ return first !== undefined && 'name' in first ? first.name : undefined;
104
+ }),
105
+ ...config.primaryKeys.map((key) => key.columns.at(0)?.name),
106
+ ...config.uniqueConstraints.map((constraint) => constraint.columns.at(0)?.name),
107
+ ...config.columns.filter((column) => column.primary || column.isUnique).map((column) => column.name),
108
+ ]);
109
+ }
110
+ /**
111
+ * Checks that every foreign key is indexed.
112
+ *
113
+ * @param config - The table.
114
+ * @returns One problem per key without.
115
+ */
116
+ function indexProblems(config) {
117
+ const indexed = leadingColumns(config);
118
+ return foreignKeyColumns(config)
119
+ .map(([first]) => first)
120
+ .filter((column) => indexed.has(column) === false)
121
+ .map((column) => `${column} is a foreign key with no index`);
122
+ }
123
+ /**
124
+ * Checks the exceptions themselves, so a list does not outlive its reason.
125
+ *
126
+ * @param configs - Every table.
127
+ * @param derived - The derived tables.
128
+ * @param legacyIds - The tables that keep an old id.
129
+ * @returns What is wrong with them.
130
+ */
131
+ function exceptionProblems(configs, derived, legacyIds) {
132
+ const byName = new Map(configs.map((config) => [config.name, config]));
133
+ const referenced = new Set(configs.flatMap((config) => config.foreignKeys.map((key) => getTableConfig(key.reference().foreignTable).name)));
134
+ const derivedProblems = Object.keys(derived).flatMap((name) => {
135
+ const config = byName.get(name);
136
+ if (config === undefined) {
137
+ return [`${name} is listed as derived and does not exist`];
138
+ }
139
+ const hasId = config.columns.some((column) => column.name === 'id');
140
+ return [
141
+ ...(hasId ? [`${name} is listed as derived and has an id`] : []),
142
+ ...(referenced.has(name) ? [`${name} is listed as derived and is referenced`] : []),
143
+ ];
144
+ });
145
+ const legacyProblems = Object.keys(legacyIds).flatMap((name) => {
146
+ const config = byName.get(name);
147
+ if (config === undefined) {
148
+ return [`${name} is listed with a legacy id and does not exist`];
149
+ }
150
+ return idProblems(config).length === 0 ? [`${name} is listed with a legacy id and has a UUIDv7 one`] : [];
151
+ });
152
+ return [...derivedProblems, ...legacyProblems];
153
+ }
package/llms.txt ADDED
@@ -0,0 +1,53 @@
1
+ # @cubicecho/server-kit
2
+
3
+ > The server code every cubicecho GraphQL backend shares: database boot, id columns and the checks that keep a schema to the standard.
4
+
5
+ Agent-facing docs for @cubicecho/server-kit: one task or concept per page, then what each package.json "exports" entry exports. Generated from _agents/docs/ and the doc comments in src/ by @cubicecho/agent-docs; edit those, not this file.
6
+
7
+ Requires Node >=22. Peer dependencies: `@electric-sql/pglite` ^0.5.0 (optional), `drizzle-orm` 1.0.0-rc.5, `postgres` ^3.4.0, `vitest` ^5.0.0 (optional).
8
+
9
+ ## Docs
10
+
11
+ - [Database boot](_agents/docs/01-database.md): `@cubicecho/server-kit/db` makes a Postgres database ready to migrate: it waits for the server, creates the database when it is missing, and refuses a server the app cannot run on.
12
+ - [Columns](_agents/docs/02-columns.md): `@cubicecho/server-kit/columns` has the Drizzle columns that keep a table to the conventions: a UUIDv7 id, moments with a time zone, and a table limited to one row.
13
+ - [Test checks](_agents/docs/03-testing.md): `@cubicecho/server-kit/testing` registers Vitest tests that hold an app to the backend standard: its tables, and the Postgres it runs.
14
+ - [Common mistakes](_agents/docs/common-mistakes.md): What goes wrong when the kit is wired up slightly differently, and the fix for each.
15
+
16
+ ## Exports: @cubicecho/server-kit/columns
17
+
18
+ - `id`: The primary key of an entity: a UUIDv7, made by the database.
19
+ - `moment`: A moment, with its time zone.
20
+ - `timestamps`: When a row was made, and when it last changed.
21
+ - `singleton`: The column that keeps a table to one row.
22
+ - `singletonRules`: The unique index and the check that make `singleton` work.
23
+
24
+ ## Exports: @cubicecho/server-kit/db
25
+
26
+ - `MIN_POSTGRES_MAJOR`: The first Postgres with `uuidv7()`, which ids default to.
27
+ - `TESTED_POSTGRES_MAJOR`: The newest Postgres this package is tested on.
28
+ - `ConnectionOptions` (type): What a postgres-js client is given besides its URL.
29
+ - `connectionOptions`: The postgres-js options a server connects with.
30
+ - `AdminClient` (type): The least boot needs of a connection to the maintenance database.
31
+ - `OpenAdmin` (type): Opens a connection to the maintenance database.
32
+ - `DATABASE_DEFAULTS`: What boot uses when the app overrides nothing.
33
+ - `DatabaseSettings` (type): Settings for reaching Postgres at boot.
34
+ - `DatabaseBootError`: Thrown when boot cannot use the database.
35
+ - `errorCode`: Reads the driver or errno code of an error, or of whatever caused it.
36
+ - `PrepareOptions` (type): How a database is made ready.
37
+ - `prepareDatabase`: Makes the database ready to migrate: waits for it, creates it when it is missing, and checks its version.
38
+ - `isPrivateHost`: Whether a host is this machine or on a private network.
39
+ - `requiresSsl`: Whether to insist on TLS for a connection string.
40
+ - `PostgresNeeds` (type): What the app needs of its Postgres.
41
+ - `requirePostgres`: Refuses a Postgres the app cannot run on, before anything is migrated.
42
+ - `Queryable` (type): Anything that can run a query: the Drizzle client on postgres-js, pg or PGlite.
43
+ - `waitForDatabase`: Waits until Postgres answers a query.
44
+
45
+ ## Exports: @cubicecho/server-kit/testing
46
+
47
+ - `PostgresFiles` (type): Where a repo says which Postgres it runs.
48
+ - `PostgresFindings` (type): What a comparison found.
49
+ - `postgresProblems`: Compares the Postgres majors a repo names with each other and with the one its tests run on.
50
+ - `SchemaExceptions` (type): Tables the id rule does not apply to.
51
+ - `schemaProblems`: Finds what breaks the table conventions.
52
+ - `checkSchemaConventions`: Registers the tests that hold a schema to the table conventions: ids, join tables, time zones and foreign-key indexes.
53
+ - `checkPostgresVersion`: Registers the test that a repo's compose files, CI and tests agree on a Postgres major.