@facilis.dev/nitro 0.1.7 → 0.1.9

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.
@@ -1,10 +1,12 @@
1
1
  import { readdir } from "node:fs/promises";
2
2
  import { join } from "node:path";
3
3
  import { applyStatements, applyViews, ensureAppRole } from "@facilis.dev/db";
4
+ import { parseSchemaApprovals, SCHEMA_APPROVALS_PATH } from "@facilis.dev/core";
4
5
  import { seedStatements } from "@facilis.dev/auth";
5
6
  import { projectRoot } from "#facilis/config";
6
7
  import dbViewModules from "#facilis/db-views";
7
8
  import { readMigrationsDir, toAuthConfig } from "./config.js";
9
+ import { reconcileDeclaredSchema } from "./schema-reconcile.js";
8
10
  import { readTextFile } from "./project-files.js";
9
11
  import { splitSqlStatements } from "./sql.js";
10
12
  import { provisionSystemRole } from "./system-role.js";
@@ -23,6 +25,16 @@ export async function bootstrapDevelopmentDatabase(db, projectConfig, warnings)
23
25
  catch (error) {
24
26
  warnings.push(warning("migration_failed", `Migrations failed: ${describe(error)}`));
25
27
  }
28
+ // D-193: the declared schema is the source of truth in dev too. The replay above keeps a
29
+ // project that still ships db/migrations working; the reconcile creates what db/schema.ts
30
+ // added since, and never drops anything the user did not confirm.
31
+ try {
32
+ const approvals = await readTextFile(join(projectRoot, SCHEMA_APPROVALS_PATH));
33
+ await reconcileDeclaredSchema(db, approvals === null ? [] : parseSchemaApprovals(approvals), warnings);
34
+ }
35
+ catch (error) {
36
+ warnings.push(warning("schema_reconcile_failed", `Schema reconcile failed: ${describe(error)}`));
37
+ }
26
38
  try {
27
39
  await applyStatements(db, seedStatements(toAuthConfig(projectConfig.auth)));
28
40
  }
@@ -0,0 +1,14 @@
1
+ import { type ManifestWarning, type SchemaSnapshot } from "@facilis.dev/core";
2
+ import { type FacilisDb, type LiveSchemaSnapshot } from "@facilis.dev/db";
3
+ /**
4
+ * The statements that bring `live` up to `declared`: missing enums, tables (with their
5
+ * foreign keys, indexes, RLS and policies) and columns, plus the drops the user approved.
6
+ * Pure, so the planner is tested without a database.
7
+ */
8
+ export declare function planReconcile(declared: SchemaSnapshot, live: LiveSchemaSnapshot, approvals: readonly string[]): string[];
9
+ /**
10
+ * Materialize the declared schema onto the dev database. A statement that fails (a NOT NULL
11
+ * column on a table with rows, an unsupported declaration) becomes a manifest warning instead
12
+ * of a failed boot: the app still starts, and /__facilis/dev/schema shows the drift.
13
+ */
14
+ export declare function reconcileDeclaredSchema(db: FacilisDb, approvals: readonly string[], warnings: ManifestWarning[]): Promise<void>;
@@ -0,0 +1,136 @@
1
+ // Dev schema reconcile (D-193, docs/MIGRATION-PLAN.md P5): the dev database is materialized
2
+ // from db/schema.ts at boot instead of from hand-written SQL, which is what lets the AI edit
3
+ // the schema without writing a migration.
4
+ //
5
+ // The reconcile is ADDITIVE by design. Tables, columns, policies and RLS that the declaration
6
+ // has and the database lacks are created with the release planner's own renderers, so a table
7
+ // created at boot and one created by a release artifact cannot drift. Destructive DDL is
8
+ // never inferred: a drop runs only when the user confirmed that exact change from the IDE and
9
+ // it is recorded in .facilis/dev/schema-approvals.json (SCHEMA_APPROVALS_PATH). An unconfirmed
10
+ // drop is skipped, so a hand edit of db/schema.ts can never delete data at boot.
11
+ //
12
+ // Everything here is dev-only: a Postgres target never reaches this module, the deploy owns
13
+ // the DDL there (db-bootstrap.ts).
14
+ import { addColumnSql, addForeignKeySql, createIndexSql, createPolicySql, createTableSql, dropColumnSql, dropTableSql, enableRlsSql, quote, quoteLiteral, } from "@facilis.dev/core";
15
+ import { applyStatements, liveSchemaSnapshot, schemaSnapshot, } from "@facilis.dev/db";
16
+ function describe(error) {
17
+ return error instanceof Error ? error.message : String(error);
18
+ }
19
+ function warning(code, message) {
20
+ return { code, message };
21
+ }
22
+ /** One line of the statement for a warning, so a failed batch is identifiable. */
23
+ function headline(statement) {
24
+ const flat = statement.replaceAll(/\s+/gu, " ").trim();
25
+ return flat.length > 120 ? flat.slice(0, 117) + "..." : flat;
26
+ }
27
+ /** `CREATE TYPE` has no IF NOT EXISTS, so the duplicate case is swallowed in a DO block. */
28
+ function createEnumSql(name, values) {
29
+ return ("DO $$ BEGIN CREATE TYPE " +
30
+ quote(name) +
31
+ " AS ENUM (" +
32
+ values.map(quoteLiteral).join(", ") +
33
+ "); EXCEPTION WHEN duplicate_object THEN NULL; END $$;");
34
+ }
35
+ function liveTablesByName(live) {
36
+ return new Map(live.tables.map((table) => [table.name, table]));
37
+ }
38
+ function columnNames(table) {
39
+ return new Set(table.columns.map((column) => column.name));
40
+ }
41
+ /**
42
+ * The statements that bring `live` up to `declared`: missing enums, tables (with their
43
+ * foreign keys, indexes, RLS and policies) and columns, plus the drops the user approved.
44
+ * Pure, so the planner is tested without a database.
45
+ */
46
+ export function planReconcile(declared, live, approvals) {
47
+ const liveByName = liveTablesByName(live);
48
+ const created = [];
49
+ const existing = [];
50
+ for (const table of declared.tables) {
51
+ if (liveByName.has(table.name))
52
+ existing.push(table);
53
+ else
54
+ created.push(table);
55
+ }
56
+ const statements = [];
57
+ for (const entry of declared.enums ?? [])
58
+ statements.push(createEnumSql(entry.name, entry.values));
59
+ for (const table of created)
60
+ statements.push(createTableSql(table));
61
+ // A table's foreign key may point at a table created in this same pass, so the constraints
62
+ // come after every CREATE TABLE.
63
+ for (const table of created) {
64
+ for (const foreignKey of table.foreignKeys) {
65
+ statements.push(addForeignKeySql(table.name, foreignKey));
66
+ }
67
+ for (const index of table.indexes ?? [])
68
+ statements.push(createIndexSql(table.name, index));
69
+ }
70
+ for (const table of created) {
71
+ if (table.rlsEnabled)
72
+ statements.push(enableRlsSql(table.name));
73
+ for (const policy of table.policies)
74
+ statements.push(createPolicySql(policy));
75
+ }
76
+ for (const table of existing) {
77
+ const current = liveByName.get(table.name);
78
+ if (current === undefined)
79
+ continue;
80
+ const columns = columnNames(current);
81
+ for (const column of table.columns) {
82
+ if (!columns.has(column.name))
83
+ statements.push(addColumnSql(table.name, column));
84
+ }
85
+ if (table.rlsEnabled && !current.rlsEnabled)
86
+ statements.push(enableRlsSql(table.name));
87
+ const policies = new Set(current.policies.map((policy) => policy.name));
88
+ for (const policy of table.policies) {
89
+ if (!policies.has(policy.name))
90
+ statements.push(createPolicySql(policy));
91
+ }
92
+ }
93
+ const approved = new Set(approvals);
94
+ for (const table of live.tables) {
95
+ const declaredTable = declared.tables.find((entry) => entry.name === table.name);
96
+ if (declaredTable === undefined) {
97
+ if (approved.has(`drops table "${table.name}"`))
98
+ statements.push(dropTableSql(table.name));
99
+ continue;
100
+ }
101
+ const columns = new Set(declaredTable.columns.map((column) => column.name));
102
+ for (const column of table.columns) {
103
+ if (columns.has(column.name))
104
+ continue;
105
+ if (approved.has(`drops column "${table.name}.${column.name}"`)) {
106
+ statements.push(dropColumnSql(table.name, column.name));
107
+ }
108
+ }
109
+ }
110
+ return statements;
111
+ }
112
+ /**
113
+ * Materialize the declared schema onto the dev database. A statement that fails (a NOT NULL
114
+ * column on a table with rows, an unsupported declaration) becomes a manifest warning instead
115
+ * of a failed boot: the app still starts, and /__facilis/dev/schema shows the drift.
116
+ */
117
+ export async function reconcileDeclaredSchema(db, approvals, warnings) {
118
+ let declared;
119
+ let live;
120
+ try {
121
+ [declared, live] = await Promise.all([schemaSnapshot(db), liveSchemaSnapshot(db)]);
122
+ }
123
+ catch (error) {
124
+ warnings.push(warning("schema_reconcile_failed", `Could not read the schema: ${describe(error)}`));
125
+ return;
126
+ }
127
+ const statements = planReconcile(declared, live, approvals);
128
+ for (const statement of statements) {
129
+ try {
130
+ await applyStatements(db, [statement]);
131
+ }
132
+ catch (error) {
133
+ warnings.push(warning("schema_reconcile_failed", `Could not apply "${headline(statement)}": ${describe(error)}`));
134
+ }
135
+ }
136
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@facilis.dev/nitro",
3
- "version": "0.1.7",
3
+ "version": "0.1.9",
4
4
  "type": "module",
5
5
  "description": "Facilis Nitro module and its Vite plugin wrapper.",
6
6
  "license": "MIT",
@@ -31,11 +31,11 @@
31
31
  }
32
32
  },
33
33
  "dependencies": {
34
- "@facilis.dev/analyze": "0.1.7",
35
- "@facilis.dev/auth": "0.1.7",
36
- "@facilis.dev/core": "0.1.7",
37
- "@facilis.dev/db": "0.1.7",
38
- "@facilis.dev/storage": "0.1.7",
34
+ "@facilis.dev/analyze": "0.1.9",
35
+ "@facilis.dev/auth": "0.1.9",
36
+ "@facilis.dev/core": "0.1.9",
37
+ "@facilis.dev/db": "0.1.9",
38
+ "@facilis.dev/storage": "0.1.9",
39
39
  "drizzle-orm": "0.45.4",
40
40
  "zod": "4.6.7"
41
41
  },
@@ -2,12 +2,14 @@ import { readdir } from "node:fs/promises";
2
2
  import { join } from "node:path";
3
3
 
4
4
  import { applyStatements, applyViews, ensureAppRole, type FacilisDb } from "@facilis.dev/db";
5
+ import { parseSchemaApprovals, SCHEMA_APPROVALS_PATH } from "@facilis.dev/core";
5
6
  import { seedStatements } from "@facilis.dev/auth";
6
7
  import type { FacilisConfig, ManifestWarning } from "@facilis.dev/core";
7
8
  import { projectRoot } from "#facilis/config";
8
9
  import dbViewModules from "#facilis/db-views";
9
10
 
10
11
  import { readMigrationsDir, toAuthConfig } from "./config.ts";
12
+ import { reconcileDeclaredSchema } from "./schema-reconcile.ts";
11
13
  import { readTextFile } from "./project-files.ts";
12
14
  import { splitSqlStatements } from "./sql.ts";
13
15
  import { provisionSystemRole } from "./system-role.ts";
@@ -30,6 +32,22 @@ export async function bootstrapDevelopmentDatabase(
30
32
  warnings.push(warning("migration_failed", `Migrations failed: ${describe(error)}`));
31
33
  }
32
34
 
35
+ // D-193: the declared schema is the source of truth in dev too. The replay above keeps a
36
+ // project that still ships db/migrations working; the reconcile creates what db/schema.ts
37
+ // added since, and never drops anything the user did not confirm.
38
+ try {
39
+ const approvals = await readTextFile(join(projectRoot, SCHEMA_APPROVALS_PATH));
40
+ await reconcileDeclaredSchema(
41
+ db,
42
+ approvals === null ? [] : parseSchemaApprovals(approvals),
43
+ warnings,
44
+ );
45
+ } catch (error) {
46
+ warnings.push(
47
+ warning("schema_reconcile_failed", `Schema reconcile failed: ${describe(error)}`),
48
+ );
49
+ }
50
+
33
51
  try {
34
52
  await applyStatements(db, seedStatements(toAuthConfig(projectConfig.auth)));
35
53
  } catch (error) {
@@ -0,0 +1,170 @@
1
+ // Dev schema reconcile (D-193, docs/MIGRATION-PLAN.md P5): the dev database is materialized
2
+ // from db/schema.ts at boot instead of from hand-written SQL, which is what lets the AI edit
3
+ // the schema without writing a migration.
4
+ //
5
+ // The reconcile is ADDITIVE by design. Tables, columns, policies and RLS that the declaration
6
+ // has and the database lacks are created with the release planner's own renderers, so a table
7
+ // created at boot and one created by a release artifact cannot drift. Destructive DDL is
8
+ // never inferred: a drop runs only when the user confirmed that exact change from the IDE and
9
+ // it is recorded in .facilis/dev/schema-approvals.json (SCHEMA_APPROVALS_PATH). An unconfirmed
10
+ // drop is skipped, so a hand edit of db/schema.ts can never delete data at boot.
11
+ //
12
+ // Everything here is dev-only: a Postgres target never reaches this module, the deploy owns
13
+ // the DDL there (db-bootstrap.ts).
14
+
15
+ import {
16
+ addColumnSql,
17
+ addForeignKeySql,
18
+ createIndexSql,
19
+ createPolicySql,
20
+ createTableSql,
21
+ dropColumnSql,
22
+ dropTableSql,
23
+ enableRlsSql,
24
+ quote,
25
+ quoteLiteral,
26
+ type ManifestWarning,
27
+ type SchemaSnapshot,
28
+ type TableSnapshot,
29
+ } from "@facilis.dev/core";
30
+ import {
31
+ applyStatements,
32
+ liveSchemaSnapshot,
33
+ schemaSnapshot,
34
+ type FacilisDb,
35
+ type LiveSchemaSnapshot,
36
+ type LiveTableSnapshot,
37
+ } from "@facilis.dev/db";
38
+ function describe(error: unknown): string {
39
+ return error instanceof Error ? error.message : String(error);
40
+ }
41
+
42
+ function warning(code: string, message: string): ManifestWarning {
43
+ return { code, message };
44
+ }
45
+
46
+ /** One line of the statement for a warning, so a failed batch is identifiable. */
47
+ function headline(statement: string): string {
48
+ const flat = statement.replaceAll(/\s+/gu, " ").trim();
49
+ return flat.length > 120 ? flat.slice(0, 117) + "..." : flat;
50
+ }
51
+
52
+ /** `CREATE TYPE` has no IF NOT EXISTS, so the duplicate case is swallowed in a DO block. */
53
+ function createEnumSql(name: string, values: readonly string[]): string {
54
+ return (
55
+ "DO $$ BEGIN CREATE TYPE " +
56
+ quote(name) +
57
+ " AS ENUM (" +
58
+ values.map(quoteLiteral).join(", ") +
59
+ "); EXCEPTION WHEN duplicate_object THEN NULL; END $$;"
60
+ );
61
+ }
62
+
63
+ function liveTablesByName(live: LiveSchemaSnapshot): Map<string, LiveTableSnapshot> {
64
+ return new Map(live.tables.map((table) => [table.name, table]));
65
+ }
66
+
67
+ function columnNames(table: LiveTableSnapshot): Set<string> {
68
+ return new Set(table.columns.map((column) => column.name));
69
+ }
70
+
71
+ /**
72
+ * The statements that bring `live` up to `declared`: missing enums, tables (with their
73
+ * foreign keys, indexes, RLS and policies) and columns, plus the drops the user approved.
74
+ * Pure, so the planner is tested without a database.
75
+ */
76
+ export function planReconcile(
77
+ declared: SchemaSnapshot,
78
+ live: LiveSchemaSnapshot,
79
+ approvals: readonly string[],
80
+ ): string[] {
81
+ const liveByName = liveTablesByName(live);
82
+ const created: TableSnapshot[] = [];
83
+ const existing: TableSnapshot[] = [];
84
+ for (const table of declared.tables) {
85
+ if (liveByName.has(table.name)) existing.push(table);
86
+ else created.push(table);
87
+ }
88
+
89
+ const statements: string[] = [];
90
+ for (const entry of declared.enums ?? [])
91
+ statements.push(createEnumSql(entry.name, entry.values));
92
+ for (const table of created) statements.push(createTableSql(table));
93
+ // A table's foreign key may point at a table created in this same pass, so the constraints
94
+ // come after every CREATE TABLE.
95
+ for (const table of created) {
96
+ for (const foreignKey of table.foreignKeys) {
97
+ statements.push(addForeignKeySql(table.name, foreignKey));
98
+ }
99
+ for (const index of table.indexes ?? []) statements.push(createIndexSql(table.name, index));
100
+ }
101
+ for (const table of created) {
102
+ if (table.rlsEnabled) statements.push(enableRlsSql(table.name));
103
+ for (const policy of table.policies) statements.push(createPolicySql(policy));
104
+ }
105
+ for (const table of existing) {
106
+ const current = liveByName.get(table.name);
107
+ if (current === undefined) continue;
108
+ const columns = columnNames(current);
109
+ for (const column of table.columns) {
110
+ if (!columns.has(column.name)) statements.push(addColumnSql(table.name, column));
111
+ }
112
+ if (table.rlsEnabled && !current.rlsEnabled) statements.push(enableRlsSql(table.name));
113
+ const policies = new Set(current.policies.map((policy) => policy.name));
114
+ for (const policy of table.policies) {
115
+ if (!policies.has(policy.name)) statements.push(createPolicySql(policy));
116
+ }
117
+ }
118
+
119
+ const approved = new Set(approvals);
120
+ for (const table of live.tables) {
121
+ const declaredTable = declared.tables.find((entry) => entry.name === table.name);
122
+ if (declaredTable === undefined) {
123
+ if (approved.has(`drops table "${table.name}"`)) statements.push(dropTableSql(table.name));
124
+ continue;
125
+ }
126
+ const columns = new Set(declaredTable.columns.map((column) => column.name));
127
+ for (const column of table.columns) {
128
+ if (columns.has(column.name)) continue;
129
+ if (approved.has(`drops column "${table.name}.${column.name}"`)) {
130
+ statements.push(dropColumnSql(table.name, column.name));
131
+ }
132
+ }
133
+ }
134
+ return statements;
135
+ }
136
+
137
+ /**
138
+ * Materialize the declared schema onto the dev database. A statement that fails (a NOT NULL
139
+ * column on a table with rows, an unsupported declaration) becomes a manifest warning instead
140
+ * of a failed boot: the app still starts, and /__facilis/dev/schema shows the drift.
141
+ */
142
+ export async function reconcileDeclaredSchema(
143
+ db: FacilisDb,
144
+ approvals: readonly string[],
145
+ warnings: ManifestWarning[],
146
+ ): Promise<void> {
147
+ let declared: SchemaSnapshot;
148
+ let live: LiveSchemaSnapshot;
149
+ try {
150
+ [declared, live] = await Promise.all([schemaSnapshot(db), liveSchemaSnapshot(db)]);
151
+ } catch (error) {
152
+ warnings.push(
153
+ warning("schema_reconcile_failed", `Could not read the schema: ${describe(error)}`),
154
+ );
155
+ return;
156
+ }
157
+ const statements = planReconcile(declared, live, approvals);
158
+ for (const statement of statements) {
159
+ try {
160
+ await applyStatements(db, [statement]);
161
+ } catch (error) {
162
+ warnings.push(
163
+ warning(
164
+ "schema_reconcile_failed",
165
+ `Could not apply "${headline(statement)}": ${describe(error)}`,
166
+ ),
167
+ );
168
+ }
169
+ }
170
+ }