postgresai 0.14.0-dev.42 → 0.14.0-dev.44

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.
Files changed (58) hide show
  1. package/bin/postgres-ai.ts +649 -310
  2. package/bun.lock +258 -0
  3. package/dist/bin/postgres-ai.js +29491 -1910
  4. package/dist/sql/01.role.sql +16 -0
  5. package/dist/sql/02.permissions.sql +37 -0
  6. package/dist/sql/03.optional_rds.sql +6 -0
  7. package/dist/sql/04.optional_self_managed.sql +8 -0
  8. package/dist/sql/05.helpers.sql +415 -0
  9. package/lib/auth-server.ts +58 -97
  10. package/lib/checkup-api.ts +175 -0
  11. package/lib/checkup.ts +833 -0
  12. package/lib/config.ts +3 -0
  13. package/lib/init.ts +106 -74
  14. package/lib/issues.ts +121 -194
  15. package/lib/mcp-server.ts +6 -17
  16. package/lib/metrics-loader.ts +156 -0
  17. package/package.json +13 -9
  18. package/sql/02.permissions.sql +9 -5
  19. package/sql/05.helpers.sql +415 -0
  20. package/test/checkup.test.ts +953 -0
  21. package/test/init.integration.test.ts +396 -0
  22. package/test/init.test.ts +345 -0
  23. package/test/schema-validation.test.ts +188 -0
  24. package/tsconfig.json +12 -20
  25. package/dist/bin/postgres-ai.d.ts +0 -3
  26. package/dist/bin/postgres-ai.d.ts.map +0 -1
  27. package/dist/bin/postgres-ai.js.map +0 -1
  28. package/dist/lib/auth-server.d.ts +0 -31
  29. package/dist/lib/auth-server.d.ts.map +0 -1
  30. package/dist/lib/auth-server.js +0 -263
  31. package/dist/lib/auth-server.js.map +0 -1
  32. package/dist/lib/config.d.ts +0 -45
  33. package/dist/lib/config.d.ts.map +0 -1
  34. package/dist/lib/config.js +0 -181
  35. package/dist/lib/config.js.map +0 -1
  36. package/dist/lib/init.d.ts +0 -85
  37. package/dist/lib/init.d.ts.map +0 -1
  38. package/dist/lib/init.js +0 -644
  39. package/dist/lib/init.js.map +0 -1
  40. package/dist/lib/issues.d.ts +0 -75
  41. package/dist/lib/issues.d.ts.map +0 -1
  42. package/dist/lib/issues.js +0 -336
  43. package/dist/lib/issues.js.map +0 -1
  44. package/dist/lib/mcp-server.d.ts +0 -9
  45. package/dist/lib/mcp-server.d.ts.map +0 -1
  46. package/dist/lib/mcp-server.js +0 -168
  47. package/dist/lib/mcp-server.js.map +0 -1
  48. package/dist/lib/pkce.d.ts +0 -32
  49. package/dist/lib/pkce.d.ts.map +0 -1
  50. package/dist/lib/pkce.js +0 -101
  51. package/dist/lib/pkce.js.map +0 -1
  52. package/dist/lib/util.d.ts +0 -27
  53. package/dist/lib/util.d.ts.map +0 -1
  54. package/dist/lib/util.js +0 -46
  55. package/dist/lib/util.js.map +0 -1
  56. package/dist/package.json +0 -46
  57. package/test/init.integration.test.cjs +0 -382
  58. package/test/init.test.cjs +0 -392
@@ -0,0 +1,345 @@
1
+ import { describe, test, expect, beforeAll } from "bun:test";
2
+ import { resolve } from "path";
3
+
4
+ // Import from source directly since we're using Bun
5
+ import * as init from "../lib/init";
6
+ const DEFAULT_MONITORING_USER = init.DEFAULT_MONITORING_USER;
7
+
8
+ function runCli(args: string[], env: Record<string, string> = {}) {
9
+ const cliPath = resolve(import.meta.dir, "..", "bin", "postgres-ai.ts");
10
+ const bunBin = typeof process.execPath === "string" && process.execPath.length > 0 ? process.execPath : "bun";
11
+ const result = Bun.spawnSync([bunBin, cliPath, ...args], {
12
+ env: { ...process.env, ...env },
13
+ });
14
+ return {
15
+ status: result.exitCode,
16
+ stdout: new TextDecoder().decode(result.stdout),
17
+ stderr: new TextDecoder().decode(result.stderr),
18
+ };
19
+ }
20
+
21
+ function runPgai(args: string[], env: Record<string, string> = {}) {
22
+ // For testing, run the CLI directly since pgai is just a thin wrapper
23
+ // In production, pgai wrapper will properly resolve and spawn the postgresai CLI
24
+ const cliPath = resolve(import.meta.dir, "..", "bin", "postgres-ai.ts");
25
+ const bunBin = typeof process.execPath === "string" && process.execPath.length > 0 ? process.execPath : "bun";
26
+ const result = Bun.spawnSync([bunBin, cliPath, ...args], {
27
+ env: { ...process.env, ...env },
28
+ });
29
+ return {
30
+ status: result.exitCode,
31
+ stdout: new TextDecoder().decode(result.stdout),
32
+ stderr: new TextDecoder().decode(result.stderr),
33
+ };
34
+ }
35
+
36
+ describe("init module", () => {
37
+ test("maskConnectionString hides password when present", () => {
38
+ const masked = init.maskConnectionString("postgresql://user:secret@localhost:5432/mydb");
39
+ expect(masked).toMatch(/postgresql:\/\/user:\*{5}@localhost:5432\/mydb/);
40
+ expect(masked).not.toMatch(/secret/);
41
+ });
42
+
43
+ test("parseLibpqConninfo parses basic host/dbname/user/port/password", () => {
44
+ const cfg = init.parseLibpqConninfo("dbname=mydb host=localhost user=alice port=5432 password=secret");
45
+ expect(cfg.database).toBe("mydb");
46
+ expect(cfg.host).toBe("localhost");
47
+ expect(cfg.user).toBe("alice");
48
+ expect(cfg.port).toBe(5432);
49
+ expect(cfg.password).toBe("secret");
50
+ });
51
+
52
+ test("parseLibpqConninfo supports quoted values", () => {
53
+ const cfg = init.parseLibpqConninfo("dbname='my db' host='local host'");
54
+ expect(cfg.database).toBe("my db");
55
+ expect(cfg.host).toBe("local host");
56
+ });
57
+
58
+ test("buildInitPlan includes a race-safe role DO block", async () => {
59
+ const plan = await init.buildInitPlan({
60
+ database: "mydb",
61
+ monitoringUser: DEFAULT_MONITORING_USER,
62
+ monitoringPassword: "pw",
63
+ includeOptionalPermissions: false,
64
+ });
65
+
66
+ expect(plan.database).toBe("mydb");
67
+ const roleStep = plan.steps.find((s: { name: string }) => s.name === "01.role");
68
+ expect(roleStep).toBeTruthy();
69
+ expect(roleStep.sql).toMatch(/do\s+\$\$/i);
70
+ expect(roleStep.sql).toMatch(/create\s+user/i);
71
+ expect(roleStep.sql).toMatch(/alter\s+user/i);
72
+ expect(plan.steps.some((s: { optional?: boolean }) => s.optional)).toBe(false);
73
+ });
74
+
75
+ test("buildInitPlan handles special characters in monitoring user and database identifiers", async () => {
76
+ const monitoringUser = 'user "with" quotes ✓';
77
+ const database = 'db name "with" quotes ✓';
78
+ const plan = await init.buildInitPlan({
79
+ database,
80
+ monitoringUser,
81
+ monitoringPassword: "pw",
82
+ includeOptionalPermissions: false,
83
+ });
84
+
85
+ const roleStep = plan.steps.find((s: { name: string }) => s.name === "01.role");
86
+ expect(roleStep).toBeTruthy();
87
+ expect(roleStep.sql).toMatch(/create\s+user\s+"user ""with"" quotes ✓"/i);
88
+ expect(roleStep.sql).toMatch(/alter\s+user\s+"user ""with"" quotes ✓"/i);
89
+
90
+ const permStep = plan.steps.find((s: { name: string }) => s.name === "02.permissions");
91
+ expect(permStep).toBeTruthy();
92
+ expect(permStep.sql).toMatch(/grant connect on database "db name ""with"" quotes ✓" to "user ""with"" quotes ✓"/i);
93
+ });
94
+
95
+ test("buildInitPlan keeps backslashes in passwords (no unintended escaping)", async () => {
96
+ const pw = String.raw`pw\with\backslash`;
97
+ const plan = await init.buildInitPlan({
98
+ database: "mydb",
99
+ monitoringUser: DEFAULT_MONITORING_USER,
100
+ monitoringPassword: pw,
101
+ includeOptionalPermissions: false,
102
+ });
103
+ const roleStep = plan.steps.find((s: { name: string }) => s.name === "01.role");
104
+ expect(roleStep).toBeTruthy();
105
+ expect(roleStep.sql).toContain(`password '${pw}'`);
106
+ });
107
+
108
+ test("buildInitPlan rejects identifiers with null bytes", async () => {
109
+ await expect(
110
+ init.buildInitPlan({
111
+ database: "mydb",
112
+ monitoringUser: "bad\0user",
113
+ monitoringPassword: "pw",
114
+ includeOptionalPermissions: false,
115
+ })
116
+ ).rejects.toThrow(/Identifier cannot contain null bytes/);
117
+ });
118
+
119
+ test("buildInitPlan rejects literals with null bytes", async () => {
120
+ await expect(
121
+ init.buildInitPlan({
122
+ database: "mydb",
123
+ monitoringUser: DEFAULT_MONITORING_USER,
124
+ monitoringPassword: "pw\0bad",
125
+ includeOptionalPermissions: false,
126
+ })
127
+ ).rejects.toThrow(/Literal cannot contain null bytes/);
128
+ });
129
+
130
+ test("buildInitPlan inlines password safely for CREATE/ALTER ROLE grammar", async () => {
131
+ const plan = await init.buildInitPlan({
132
+ database: "mydb",
133
+ monitoringUser: DEFAULT_MONITORING_USER,
134
+ monitoringPassword: "pa'ss",
135
+ includeOptionalPermissions: false,
136
+ });
137
+ const step = plan.steps.find((s: { name: string }) => s.name === "01.role");
138
+ expect(step).toBeTruthy();
139
+ expect(step.sql).toMatch(/password 'pa''ss'/);
140
+ expect(step.params).toBeUndefined();
141
+ });
142
+
143
+ test("buildInitPlan includes optional steps when enabled", async () => {
144
+ const plan = await init.buildInitPlan({
145
+ database: "mydb",
146
+ monitoringUser: DEFAULT_MONITORING_USER,
147
+ monitoringPassword: "pw",
148
+ includeOptionalPermissions: true,
149
+ });
150
+ expect(plan.steps.some((s: { optional?: boolean }) => s.optional)).toBe(true);
151
+ });
152
+
153
+ test("resolveAdminConnection accepts positional URI", () => {
154
+ const r = init.resolveAdminConnection({ conn: "postgresql://u:p@h:5432/d" });
155
+ expect(r.clientConfig.connectionString).toBeTruthy();
156
+ expect(r.display).not.toMatch(/:p@/);
157
+ });
158
+
159
+ test("resolveAdminConnection accepts positional conninfo", () => {
160
+ const r = init.resolveAdminConnection({ conn: "dbname=mydb host=localhost user=alice" });
161
+ expect(r.clientConfig.database).toBe("mydb");
162
+ expect(r.clientConfig.host).toBe("localhost");
163
+ expect(r.clientConfig.user).toBe("alice");
164
+ });
165
+
166
+ test("resolveAdminConnection rejects invalid psql-like port", () => {
167
+ expect(() => init.resolveAdminConnection({ host: "localhost", port: "abc", username: "u", dbname: "d" }))
168
+ .toThrow(/Invalid port value/);
169
+ });
170
+
171
+ test("resolveAdminConnection rejects when only PGPASSWORD is provided (no connection details)", () => {
172
+ expect(() => init.resolveAdminConnection({ envPassword: "pw" })).toThrow(/Connection is required/);
173
+ });
174
+
175
+ test("resolveAdminConnection rejects when connection is missing", () => {
176
+ expect(() => init.resolveAdminConnection({})).toThrow(/Connection is required/);
177
+ });
178
+
179
+ test("resolveMonitoringPassword auto-generates a strong, URL-safe password by default", async () => {
180
+ const r = await init.resolveMonitoringPassword({ monitoringUser: DEFAULT_MONITORING_USER });
181
+ expect(r.generated).toBe(true);
182
+ expect(typeof r.password).toBe("string");
183
+ expect(r.password.length).toBeGreaterThanOrEqual(30);
184
+ expect(r.password).toMatch(/^[A-Za-z0-9_-]+$/);
185
+ });
186
+
187
+ test("applyInitPlan preserves Postgres error fields on step failures", async () => {
188
+ const plan = {
189
+ monitoringUser: DEFAULT_MONITORING_USER,
190
+ database: "mydb",
191
+ steps: [{ name: "01.role", sql: "select 1" }],
192
+ };
193
+
194
+ const pgErr = Object.assign(new Error("permission denied to create role"), {
195
+ code: "42501",
196
+ detail: "some detail",
197
+ hint: "some hint",
198
+ schema: "pg_catalog",
199
+ table: "pg_roles",
200
+ constraint: "some_constraint",
201
+ routine: "aclcheck_error",
202
+ });
203
+
204
+ const calls: string[] = [];
205
+ const client = {
206
+ query: async (sql: string) => {
207
+ calls.push(sql);
208
+ if (sql === "begin;") return { rowCount: 1 };
209
+ if (sql === "rollback;") return { rowCount: 1 };
210
+ if (sql === "select 1") throw pgErr;
211
+ throw new Error(`unexpected sql: ${sql}`);
212
+ },
213
+ };
214
+
215
+ try {
216
+ await init.applyInitPlan({ client: client as any, plan: plan as any });
217
+ expect(true).toBe(false); // Should not reach here
218
+ } catch (e: any) {
219
+ expect(e).toBeInstanceOf(Error);
220
+ expect(e.message).toMatch(/Failed at step "01\.role":/);
221
+ expect(e.code).toBe("42501");
222
+ expect(e.detail).toBe("some detail");
223
+ expect(e.hint).toBe("some hint");
224
+ expect(e.schema).toBe("pg_catalog");
225
+ expect(e.table).toBe("pg_roles");
226
+ expect(e.constraint).toBe("some_constraint");
227
+ expect(e.routine).toBe("aclcheck_error");
228
+ }
229
+
230
+ expect(calls).toEqual(["begin;", "select 1", "rollback;"]);
231
+ });
232
+
233
+ test("verifyInitSetup runs inside a repeatable read snapshot and rolls back", async () => {
234
+ const calls: string[] = [];
235
+ const client = {
236
+ query: async (sql: string, params?: any) => {
237
+ calls.push(String(sql));
238
+
239
+ if (String(sql).toLowerCase().startsWith("begin isolation level repeatable read")) {
240
+ return { rowCount: 1, rows: [] };
241
+ }
242
+ if (String(sql).toLowerCase() === "rollback;") {
243
+ return { rowCount: 1, rows: [] };
244
+ }
245
+ if (String(sql).includes("select rolconfig")) {
246
+ return { rowCount: 1, rows: [{ rolconfig: ['search_path=postgres_ai, "$user", public, pg_catalog'] }] };
247
+ }
248
+ if (String(sql).includes("from pg_catalog.pg_roles")) {
249
+ return { rowCount: 1, rows: [] };
250
+ }
251
+ if (String(sql).includes("has_database_privilege")) {
252
+ return { rowCount: 1, rows: [{ ok: true }] };
253
+ }
254
+ if (String(sql).includes("pg_has_role")) {
255
+ return { rowCount: 1, rows: [{ ok: true }] };
256
+ }
257
+ if (String(sql).includes("has_table_privilege") && String(sql).includes("pg_catalog.pg_index")) {
258
+ return { rowCount: 1, rows: [{ ok: true }] };
259
+ }
260
+ if (String(sql).includes("to_regclass('postgres_ai.pg_statistic')")) {
261
+ return { rowCount: 1, rows: [{ ok: true }] };
262
+ }
263
+ if (String(sql).includes("has_table_privilege") && String(sql).includes("postgres_ai.pg_statistic")) {
264
+ return { rowCount: 1, rows: [{ ok: true }] };
265
+ }
266
+ if (String(sql).includes("has_function_privilege")) {
267
+ return { rowCount: 1, rows: [{ ok: true }] };
268
+ }
269
+ if (String(sql).includes("has_schema_privilege")) {
270
+ return { rowCount: 1, rows: [{ ok: true }] };
271
+ }
272
+
273
+ throw new Error(`unexpected sql: ${sql} params=${JSON.stringify(params)}`);
274
+ },
275
+ };
276
+
277
+ const r = await init.verifyInitSetup({
278
+ client: client as any,
279
+ database: "mydb",
280
+ monitoringUser: DEFAULT_MONITORING_USER,
281
+ includeOptionalPermissions: false,
282
+ });
283
+ expect(r.ok).toBe(true);
284
+ expect(r.missingRequired.length).toBe(0);
285
+
286
+ expect(calls.length).toBeGreaterThan(2);
287
+ expect(calls[0].toLowerCase()).toMatch(/^begin isolation level repeatable read/);
288
+ expect(calls[calls.length - 1].toLowerCase()).toBe("rollback;");
289
+ });
290
+
291
+ test("redactPasswordsInSql redacts password literals with embedded quotes", async () => {
292
+ const plan = await init.buildInitPlan({
293
+ database: "mydb",
294
+ monitoringUser: DEFAULT_MONITORING_USER,
295
+ monitoringPassword: "pa'ss",
296
+ includeOptionalPermissions: false,
297
+ });
298
+ const step = plan.steps.find((s: { name: string }) => s.name === "01.role");
299
+ expect(step).toBeTruthy();
300
+ const redacted = init.redactPasswordsInSql(step.sql);
301
+ expect(redacted).toMatch(/password '<redacted>'/i);
302
+ });
303
+ });
304
+
305
+ describe("CLI commands", () => {
306
+ test("cli: prepare-db with missing connection prints help/options", () => {
307
+ const r = runCli(["prepare-db"]);
308
+ expect(r.status).not.toBe(0);
309
+ expect(r.stderr).toMatch(/--print-sql/);
310
+ expect(r.stderr).toMatch(/--monitoring-user/);
311
+ });
312
+
313
+ test("cli: prepare-db --print-sql works without connection (offline mode)", () => {
314
+ const r = runCli(["prepare-db", "--print-sql", "-d", "mydb", "--password", "monpw"]);
315
+ expect(r.status).toBe(0);
316
+ expect(r.stdout).toMatch(/SQL plan \(offline; not connected\)/);
317
+ expect(r.stdout).toMatch(new RegExp(`grant connect on database "mydb" to "${DEFAULT_MONITORING_USER}"`, "i"));
318
+ });
319
+
320
+ test("pgai wrapper forwards to postgresai CLI", () => {
321
+ const r = runPgai(["--help"]);
322
+ expect(r.status).toBe(0);
323
+ expect(r.stdout).toMatch(/postgresai|PostgresAI/i);
324
+ });
325
+
326
+ test("cli: prepare-db command exists and shows help", () => {
327
+ const r = runCli(["prepare-db", "--help"]);
328
+ expect(r.status).toBe(0);
329
+ expect(r.stdout).toMatch(/monitoring user/i);
330
+ expect(r.stdout).toMatch(/--print-sql/);
331
+ });
332
+
333
+ test("cli: mon local-install command exists and shows help", () => {
334
+ const r = runCli(["mon", "local-install", "--help"]);
335
+ expect(r.status).toBe(0);
336
+ expect(r.stdout).toMatch(/--demo/);
337
+ expect(r.stdout).toMatch(/--api-key/);
338
+ });
339
+
340
+ test("cli: auth login --help shows --set-key option", () => {
341
+ const r = runCli(["auth", "login", "--help"]);
342
+ expect(r.status).toBe(0);
343
+ expect(r.stdout).toMatch(/--set-key/);
344
+ });
345
+ });
@@ -0,0 +1,188 @@
1
+ /**
2
+ * JSON Schema validation tests for H001, H002, H004 express checkup reports.
3
+ * These tests validate that the generated reports match the schemas in reporter/schemas/.
4
+ */
5
+ import { describe, test, expect } from "bun:test";
6
+ import { resolve } from "path";
7
+ import { readFileSync } from "fs";
8
+ import Ajv2020 from "ajv/dist/2020";
9
+
10
+ import * as checkup from "../lib/checkup";
11
+
12
+ const ajv = new Ajv2020({ allErrors: true, strict: false });
13
+ const schemasDir = resolve(import.meta.dir, "../../reporter/schemas");
14
+
15
+ function loadSchema(checkId: string): object {
16
+ const schemaPath = resolve(schemasDir, `${checkId}.schema.json`);
17
+ return JSON.parse(readFileSync(schemaPath, "utf8"));
18
+ }
19
+
20
+ function validateReport(report: any, checkId: string): { valid: boolean; errors: string[] } {
21
+ const schema = loadSchema(checkId);
22
+ const validate = ajv.compile(schema);
23
+ const valid = validate(report);
24
+ const errors = validate.errors?.map(e => `${e.instancePath}: ${e.message}`) || [];
25
+ return { valid: !!valid, errors };
26
+ }
27
+
28
+ // Mock client for testing
29
+ function createMockClient(options: {
30
+ versionRows?: any[];
31
+ invalidIndexesRows?: any[];
32
+ unusedIndexesRows?: any[];
33
+ redundantIndexesRows?: any[];
34
+ } = {}) {
35
+ const {
36
+ versionRows = [
37
+ { name: "server_version", setting: "16.3" },
38
+ { name: "server_version_num", setting: "160003" },
39
+ ],
40
+ invalidIndexesRows = [],
41
+ unusedIndexesRows = [],
42
+ redundantIndexesRows = [],
43
+ } = options;
44
+
45
+ return {
46
+ query: async (sql: string) => {
47
+ if (sql.includes("server_version") && sql.includes("server_version_num") && !sql.includes("order by")) {
48
+ return { rows: versionRows };
49
+ }
50
+ if (sql.includes("current_database()") && sql.includes("pg_database_size")) {
51
+ return { rows: [{ datname: "testdb", size_bytes: "1073741824" }] };
52
+ }
53
+ if (sql.includes("stats_reset") && sql.includes("pg_stat_database")) {
54
+ return { rows: [{
55
+ stats_reset_epoch: "1704067200",
56
+ stats_reset_time: "2024-01-01 00:00:00+00",
57
+ days_since_reset: "30",
58
+ postmaster_startup_epoch: "1704067200",
59
+ postmaster_startup_time: "2024-01-01 00:00:00+00"
60
+ }] };
61
+ }
62
+ if (sql.includes("indisvalid = false")) {
63
+ return { rows: invalidIndexesRows };
64
+ }
65
+ if (sql.includes("Never Used Indexes") && sql.includes("idx_scan = 0")) {
66
+ return { rows: unusedIndexesRows };
67
+ }
68
+ if (sql.includes("redundant_indexes") && sql.includes("columns like")) {
69
+ return { rows: redundantIndexesRows };
70
+ }
71
+ throw new Error(`Unexpected query: ${sql}`);
72
+ },
73
+ };
74
+ }
75
+
76
+ describe("H001 schema validation", () => {
77
+ test("H001 report with empty data validates against schema", async () => {
78
+ const mockClient = createMockClient({ invalidIndexesRows: [] });
79
+ const report = await checkup.generateH001(mockClient as any, "node-01");
80
+
81
+ const result = validateReport(report, "H001");
82
+ if (!result.valid) {
83
+ console.error("H001 validation errors:", result.errors);
84
+ }
85
+ expect(result.valid).toBe(true);
86
+ });
87
+
88
+ test("H001 report with data validates against schema", async () => {
89
+ const mockClient = createMockClient({
90
+ invalidIndexesRows: [
91
+ {
92
+ schema_name: "public",
93
+ table_name: "users",
94
+ index_name: "users_email_idx",
95
+ relation_name: "users",
96
+ index_size_bytes: "1048576",
97
+ supports_fk: false
98
+ },
99
+ ],
100
+ });
101
+ const report = await checkup.generateH001(mockClient as any, "node-01");
102
+
103
+ const result = validateReport(report, "H001");
104
+ if (!result.valid) {
105
+ console.error("H001 validation errors:", result.errors);
106
+ }
107
+ expect(result.valid).toBe(true);
108
+ });
109
+ });
110
+
111
+ describe("H002 schema validation", () => {
112
+ test("H002 report with empty data validates against schema", async () => {
113
+ const mockClient = createMockClient({ unusedIndexesRows: [] });
114
+ const report = await checkup.generateH002(mockClient as any, "node-01");
115
+
116
+ const result = validateReport(report, "H002");
117
+ if (!result.valid) {
118
+ console.error("H002 validation errors:", result.errors);
119
+ }
120
+ expect(result.valid).toBe(true);
121
+ });
122
+
123
+ test("H002 report with data validates against schema", async () => {
124
+ const mockClient = createMockClient({
125
+ unusedIndexesRows: [
126
+ {
127
+ schema_name: "public",
128
+ table_name: "logs",
129
+ index_name: "logs_created_idx",
130
+ index_definition: "CREATE INDEX logs_created_idx ON public.logs USING btree (created_at)",
131
+ reason: "Never Used Indexes",
132
+ idx_scan: "0",
133
+ index_size_bytes: "8388608",
134
+ idx_is_btree: true,
135
+ supports_fk: false
136
+ },
137
+ ],
138
+ });
139
+ const report = await checkup.generateH002(mockClient as any, "node-01");
140
+
141
+ const result = validateReport(report, "H002");
142
+ if (!result.valid) {
143
+ console.error("H002 validation errors:", result.errors);
144
+ }
145
+ expect(result.valid).toBe(true);
146
+ });
147
+ });
148
+
149
+ describe("H004 schema validation", () => {
150
+ test("H004 report with empty data validates against schema", async () => {
151
+ const mockClient = createMockClient({ redundantIndexesRows: [] });
152
+ const report = await checkup.generateH004(mockClient as any, "node-01");
153
+
154
+ const result = validateReport(report, "H004");
155
+ if (!result.valid) {
156
+ console.error("H004 validation errors:", result.errors);
157
+ }
158
+ expect(result.valid).toBe(true);
159
+ });
160
+
161
+ test("H004 report with data validates against schema", async () => {
162
+ const mockClient = createMockClient({
163
+ redundantIndexesRows: [
164
+ {
165
+ schema_name: "public",
166
+ table_name: "orders",
167
+ index_name: "orders_user_id_idx",
168
+ relation_name: "orders",
169
+ access_method: "btree",
170
+ reason: "public.orders_user_id_created_idx",
171
+ index_size_bytes: "2097152",
172
+ table_size_bytes: "16777216",
173
+ index_usage: "0",
174
+ supports_fk: false,
175
+ index_definition: "CREATE INDEX orders_user_id_idx ON public.orders USING btree (user_id)"
176
+ },
177
+ ],
178
+ });
179
+ const report = await checkup.generateH004(mockClient as any, "node-01");
180
+
181
+ const result = validateReport(report, "H004");
182
+ if (!result.valid) {
183
+ console.error("H004 validation errors:", result.errors);
184
+ }
185
+ expect(result.valid).toBe(true);
186
+ });
187
+ });
188
+
package/tsconfig.json CHANGED
@@ -1,28 +1,20 @@
1
1
  {
2
2
  "compilerOptions": {
3
- "target": "ES2020",
4
- "module": "node16",
5
- "lib": ["ES2020"],
6
- "outDir": "./dist",
7
- "rootDir": "./",
3
+ "target": "ESNext",
4
+ "module": "ESNext",
5
+ "moduleResolution": "bundler",
6
+ "lib": ["ESNext"],
7
+ "types": ["bun-types"],
8
8
  "strict": true,
9
9
  "esModuleInterop": true,
10
10
  "skipLibCheck": true,
11
- "forceConsistentCasingInFileNames": true,
11
+ "noEmit": true,
12
12
  "resolveJsonModule": true,
13
- "declaration": true,
14
- "declarationMap": true,
15
- "sourceMap": true,
16
- "moduleResolution": "node16",
17
- "types": ["node"]
13
+ "allowImportingTsExtensions": true,
14
+ "verbatimModuleSyntax": false,
15
+ "allowSyntheticDefaultImports": true,
16
+ "forceConsistentCasingInFileNames": true
18
17
  },
19
- "include": [
20
- "bin/**/*",
21
- "lib/**/*"
22
- ],
23
- "exclude": [
24
- "node_modules",
25
- "dist"
26
- ]
18
+ "include": ["bin/**/*", "lib/**/*", "test/**/*"],
19
+ "exclude": ["node_modules", "dist"]
27
20
  }
28
-
@@ -1,3 +0,0 @@
1
- #!/usr/bin/env node
2
- export {};
3
- //# sourceMappingURL=postgres-ai.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"postgres-ai.d.ts","sourceRoot":"","sources":["../../bin/postgres-ai.ts"],"names":[],"mappings":""}