@flytedesk/app-kit 11.4.0 → 12.0.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 +138 -2
- package/dist/auth/errors.d.ts +10 -0
- package/dist/auth/errors.js +14 -0
- package/dist/auth/errors.js.map +1 -1
- package/dist/auth/index.d.ts +1 -0
- package/dist/auth/index.js +1 -0
- package/dist/auth/index.js.map +1 -1
- package/dist/auth/people/lookup.d.ts +32 -0
- package/dist/auth/people/lookup.js +81 -0
- package/dist/auth/people/lookup.js.map +1 -0
- package/dist/auth/prisma/prismaAuthStore.js +1 -6
- package/dist/auth/prisma/prismaAuthStore.js.map +1 -1
- package/dist/auth/revocationReasons.d.ts +4 -0
- package/dist/auth/revocationReasons.js +10 -0
- package/dist/auth/revocationReasons.js.map +1 -0
- package/dist/chat/tools/index.d.ts +38 -0
- package/dist/chat/tools/index.js +60 -0
- package/dist/chat/tools/index.js.map +1 -0
- package/dist/cli/auth-adopt.d.ts +13 -0
- package/dist/cli/auth-adopt.js +201 -0
- package/dist/cli/auth-adopt.js.map +1 -0
- package/dist/cli/auth-sync.js +2 -1
- package/dist/cli/auth-sync.js.map +1 -1
- package/dist/cli/sync-engine.d.ts +8 -0
- package/dist/cli/sync-engine.js +155 -21
- package/dist/cli/sync-engine.js.map +1 -1
- package/dist/flytebot/client.d.ts +66 -0
- package/dist/flytebot/client.js +377 -0
- package/dist/flytebot/client.js.map +1 -0
- package/dist/flytebot/env.d.ts +11 -0
- package/dist/flytebot/env.js +25 -0
- package/dist/flytebot/env.js.map +1 -0
- package/dist/flytebot/error.d.ts +36 -0
- package/dist/flytebot/error.js +60 -0
- package/dist/flytebot/error.js.map +1 -0
- package/dist/flytebot/index.d.ts +32 -0
- package/dist/flytebot/index.js +28 -0
- package/dist/flytebot/index.js.map +1 -0
- package/dist/flytebot/sse.d.ts +11 -0
- package/dist/flytebot/sse.js +55 -0
- package/dist/flytebot/sse.js.map +1 -0
- package/dist/flytebot/testing/fake.d.ts +77 -0
- package/dist/flytebot/testing/fake.js +399 -0
- package/dist/flytebot/testing/fake.js.map +1 -0
- package/dist/flytebot/testing/index.d.ts +18 -0
- package/dist/flytebot/testing/index.js +18 -0
- package/dist/flytebot/testing/index.js.map +1 -0
- package/dist/flytebot/webhook.d.ts +24 -0
- package/dist/flytebot/webhook.js +63 -0
- package/dist/flytebot/webhook.js.map +1 -0
- package/dist/spa-server/index.d.ts +8 -16
- package/dist/spa-server/index.js +36 -4
- package/dist/spa-server/index.js.map +1 -1
- package/package.json +17 -2
- package/prisma/fragments/auth.prisma +9 -3
- package/prisma/migrations/0004_app_kit_auth_init/migration.sql +74 -41
- package/prisma/migrations/manifest.json +1 -1
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* auth-sync adopt (AK-63) — the Prisma migration that turns an app's EXISTING auth tables
|
|
3
|
+
* into the auth fragment's (`prisma/fragments/auth.prisma`), keeping every row.
|
|
4
|
+
*
|
|
5
|
+
* An app that already has its own session / refresh-token / audit tables (flytebot,
|
|
6
|
+
* sms-app, media-planner) cannot `CREATE` the fragment's tables next to them: the tables
|
|
7
|
+
* would be duplicates, and the fragment's models would point at empty ones. Instead the
|
|
8
|
+
* app swaps its own models for the fragment's and applies THIS migration, which renames
|
|
9
|
+
* its tables, columns, keys and indexes to the fragment's names and retypes the columns
|
|
10
|
+
* the fragment types differently (timestamps become `timestamp(3)`, an enum
|
|
11
|
+
* `revoked_reason` becomes text). It is a normal Prisma migration written into the app's
|
|
12
|
+
* `prisma/migrations`, applied by the app's own `prisma migrate deploy` like any other
|
|
13
|
+
* and ordered by its timestamp after the app's earlier migrations; this CLI never
|
|
14
|
+
* executes SQL.
|
|
15
|
+
*
|
|
16
|
+
* The migration's end state is the fragment's SQL (prisma/migrations/0004_app_kit_auth_init):
|
|
17
|
+
* `auth-adopt.integration.test.ts` migrates seeded old-shape tables and diffs the result
|
|
18
|
+
* against a database built from that SQL. Extra columns the app keeps on its tables are
|
|
19
|
+
* left alone.
|
|
20
|
+
*/
|
|
21
|
+
import { readFileSync } from "node:fs";
|
|
22
|
+
import { REVOCATION_REASONS } from "../auth/revocationReasons.js";
|
|
23
|
+
const SESSION = "app_kit_idp_session";
|
|
24
|
+
const REFRESH_TOKEN = "app_kit_refresh_token";
|
|
25
|
+
const AUDIT_LOG = "app_kit_auth_audit_log";
|
|
26
|
+
const TABLES = [
|
|
27
|
+
{
|
|
28
|
+
name: SESSION,
|
|
29
|
+
columns: [
|
|
30
|
+
{ name: "id", type: "text" },
|
|
31
|
+
{ name: "subject", type: "text" },
|
|
32
|
+
{ name: "name", type: "text" },
|
|
33
|
+
{ name: "email", type: "text" },
|
|
34
|
+
{ name: "idp_access_token", type: "text" },
|
|
35
|
+
{ name: "idp_access_token_expires_at", type: "timestamp" },
|
|
36
|
+
{ name: "idp_refresh_token", type: "text", nullable: true },
|
|
37
|
+
{ name: "id_token", type: "text" },
|
|
38
|
+
{ name: "created_at", type: "timestamp", defaultNow: true },
|
|
39
|
+
],
|
|
40
|
+
indexes: [],
|
|
41
|
+
checks: {},
|
|
42
|
+
},
|
|
43
|
+
{
|
|
44
|
+
name: REFRESH_TOKEN,
|
|
45
|
+
columns: [
|
|
46
|
+
{ name: "id", type: "text" },
|
|
47
|
+
{ name: "family_id", type: "text" },
|
|
48
|
+
{ name: "user_id", type: "text" },
|
|
49
|
+
{ name: "token_hash", type: "text" },
|
|
50
|
+
{ name: "idp_session_id", type: "text" },
|
|
51
|
+
{ name: "revoked_at", type: "timestamp", nullable: true },
|
|
52
|
+
{ name: "revoked_reason", type: "text", nullable: true },
|
|
53
|
+
{ name: "expires_at", type: "timestamp" },
|
|
54
|
+
{ name: "user_agent", type: "text", nullable: true },
|
|
55
|
+
{ name: "ip", type: "text" },
|
|
56
|
+
{ name: "replaces_id", type: "text", nullable: true },
|
|
57
|
+
{ name: "created_at", type: "timestamp", defaultNow: true },
|
|
58
|
+
],
|
|
59
|
+
indexes: ["family_id", "replaces_id", "idp_session_id"],
|
|
60
|
+
unique: "token_hash",
|
|
61
|
+
foreignKey: { column: "idp_session_id", references: SESSION },
|
|
62
|
+
checks: {
|
|
63
|
+
app_kit_refresh_token_revocation_complete: `("revoked_at" IS NULL) = ("revoked_reason" IS NULL)`,
|
|
64
|
+
app_kit_refresh_token_revoked_reason_valid: `"revoked_reason" IN (${REVOCATION_REASONS.map((v) => `'${v}'`).join(", ")})`,
|
|
65
|
+
},
|
|
66
|
+
},
|
|
67
|
+
{
|
|
68
|
+
name: AUDIT_LOG,
|
|
69
|
+
columns: [
|
|
70
|
+
{ name: "id", type: "text" },
|
|
71
|
+
{ name: "family_id", type: "text" },
|
|
72
|
+
{ name: "reason", type: "text" },
|
|
73
|
+
{ name: "rotated_at", type: "timestamp" },
|
|
74
|
+
{ name: "ip", type: "text", nullable: true },
|
|
75
|
+
{ name: "user_agent", type: "text", nullable: true },
|
|
76
|
+
{ name: "created_at", type: "timestamp", defaultNow: true },
|
|
77
|
+
],
|
|
78
|
+
indexes: ["family_id"],
|
|
79
|
+
checks: {},
|
|
80
|
+
},
|
|
81
|
+
];
|
|
82
|
+
const IDENTIFIER = /^[a-z_][a-z0-9_]*$/;
|
|
83
|
+
function identifier(value, what) {
|
|
84
|
+
if (typeof value !== "string" || !IDENTIFIER.test(value)) {
|
|
85
|
+
throw new Error(`${what} must be a lower-case SQL identifier ([a-z_][a-z0-9_]*), got ${JSON.stringify(value)}`);
|
|
86
|
+
}
|
|
87
|
+
return value;
|
|
88
|
+
}
|
|
89
|
+
/** Reads and validates the mapping file; every problem is a thrown Error naming it. */
|
|
90
|
+
export function readAdoptMapping(file) {
|
|
91
|
+
const raw = JSON.parse(readFileSync(file, "utf8"));
|
|
92
|
+
if (typeof raw !== "object" || raw === null)
|
|
93
|
+
throw new Error(`${file}: expected a JSON object`);
|
|
94
|
+
const { tables, columns, ...extra } = raw;
|
|
95
|
+
if (Object.keys(extra).length > 0) {
|
|
96
|
+
throw new Error(`${file}: unknown key(s) ${Object.keys(extra).join(", ")} (expected "tables" and "columns")`);
|
|
97
|
+
}
|
|
98
|
+
const fragmentTables = TABLES.map((t) => t.name);
|
|
99
|
+
if (typeof tables !== "object" || tables === null) {
|
|
100
|
+
throw new Error(`${file}: "tables" must map each of ${fragmentTables.join(", ")} to your existing table`);
|
|
101
|
+
}
|
|
102
|
+
const mappedTables = {};
|
|
103
|
+
for (const name of fragmentTables) {
|
|
104
|
+
mappedTables[name] = identifier(tables[name], `${file}: tables.${name}`);
|
|
105
|
+
}
|
|
106
|
+
for (const key of Object.keys(tables)) {
|
|
107
|
+
if (!fragmentTables.includes(key))
|
|
108
|
+
throw new Error(`${file}: tables.${key} is not a fragment table (${fragmentTables.join(", ")})`);
|
|
109
|
+
}
|
|
110
|
+
const mappedColumns = {};
|
|
111
|
+
if (columns !== undefined) {
|
|
112
|
+
if (typeof columns !== "object" || columns === null)
|
|
113
|
+
throw new Error(`${file}: "columns" must be an object`);
|
|
114
|
+
for (const [table, map] of Object.entries(columns)) {
|
|
115
|
+
const spec = TABLES.find((t) => t.name === table);
|
|
116
|
+
if (!spec)
|
|
117
|
+
throw new Error(`${file}: columns.${table} is not a fragment table (${fragmentTables.join(", ")})`);
|
|
118
|
+
if (typeof map !== "object" || map === null)
|
|
119
|
+
throw new Error(`${file}: columns.${table} must be an object`);
|
|
120
|
+
mappedColumns[table] = {};
|
|
121
|
+
for (const [column, existing] of Object.entries(map)) {
|
|
122
|
+
if (!spec.columns.some((c) => c.name === column)) {
|
|
123
|
+
throw new Error(`${file}: columns.${table}.${column} is not a column of ${table}`);
|
|
124
|
+
}
|
|
125
|
+
mappedColumns[table][column] = identifier(existing, `${file}: columns.${table}.${column}`);
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
return { tables: mappedTables, columns: mappedColumns };
|
|
130
|
+
}
|
|
131
|
+
const q = (name) => `"${name}"`;
|
|
132
|
+
/** Runs `body` (PL/pgSQL, with `n text` declared) as one anonymous block. */
|
|
133
|
+
function doBlock(body) {
|
|
134
|
+
return `DO $adopt$\nDECLARE n text;\nBEGIN\n${body}\nEND\n$adopt$;`;
|
|
135
|
+
}
|
|
136
|
+
/** The migration SQL for `mapping`: the app's tables become the fragment's. */
|
|
137
|
+
export function buildAdoptSql(mapping) {
|
|
138
|
+
const out = [
|
|
139
|
+
`-- Adopt the app-kit auth fragment (generated by auth-sync adopt).\n--\n-- Renames this app's existing auth tables, columns, keys and indexes to the fragment's\n-- (prisma/fragments/auth.prisma) and retypes the columns it types differently. Rows stay.`,
|
|
140
|
+
];
|
|
141
|
+
// Every foreign key goes first: retyping a key column (a uuid id becoming text) is refused
|
|
142
|
+
// while a foreign key still joins it to a column of the old type. The fragment's is added
|
|
143
|
+
// back once its table is done.
|
|
144
|
+
for (const table of TABLES) {
|
|
145
|
+
const fk = table.foreignKey;
|
|
146
|
+
if (!fk)
|
|
147
|
+
continue;
|
|
148
|
+
out.push(doBlock(` FOR n IN SELECT conname FROM pg_constraint c WHERE c.conrelid = '${q(mapping.tables[table.name])}'::regclass AND c.contype = 'f'\n AND c.conkey = ARRAY[(SELECT attnum FROM pg_attribute WHERE attrelid = c.conrelid AND attname = '${mapping.columns?.[table.name]?.[fk.column] ?? fk.column}')]\n LOOP\n EXECUTE format('ALTER TABLE %I DROP CONSTRAINT %I', '${mapping.tables[table.name]}', n);\n END LOOP;`));
|
|
149
|
+
}
|
|
150
|
+
for (const table of TABLES) {
|
|
151
|
+
const current = mapping.tables[table.name];
|
|
152
|
+
const renames = mapping.columns?.[table.name] ?? {};
|
|
153
|
+
const lines = [];
|
|
154
|
+
if (current !== table.name)
|
|
155
|
+
lines.push(`ALTER TABLE ${q(current)} RENAME TO ${q(table.name)};`);
|
|
156
|
+
for (const [column, existing] of Object.entries(renames)) {
|
|
157
|
+
if (existing !== column)
|
|
158
|
+
lines.push(`ALTER TABLE ${q(table.name)} RENAME COLUMN ${q(existing)} TO ${q(column)};`);
|
|
159
|
+
}
|
|
160
|
+
for (const col of table.columns) {
|
|
161
|
+
const t = `ALTER TABLE ${q(table.name)} ALTER COLUMN ${q(col.name)}`;
|
|
162
|
+
if (col.defaultNow)
|
|
163
|
+
lines.push(`${t} DROP DEFAULT;`);
|
|
164
|
+
if (col.type === "text") {
|
|
165
|
+
lines.push(`${t} TYPE TEXT USING ${q(col.name)}::text;`);
|
|
166
|
+
}
|
|
167
|
+
else {
|
|
168
|
+
// A timestamptz column holds instants: read them as UTC, which is what Prisma writes.
|
|
169
|
+
// A plain timestamp keeps its value and only loses the precision beyond 3 digits.
|
|
170
|
+
lines.push(doBlock(` SELECT data_type INTO n FROM information_schema.columns\n WHERE table_schema = current_schema() AND table_name = '${table.name}' AND column_name = '${col.name}';\n IF n = 'timestamp with time zone' THEN\n ALTER TABLE ${q(table.name)} ALTER COLUMN ${q(col.name)} TYPE TIMESTAMP(3) USING (${q(col.name)} AT TIME ZONE 'UTC');\n ELSE\n ALTER TABLE ${q(table.name)} ALTER COLUMN ${q(col.name)} TYPE TIMESTAMP(3);\n END IF;`));
|
|
171
|
+
}
|
|
172
|
+
lines.push(`${t} ${col.nullable ? "DROP" : "SET"} NOT NULL;`);
|
|
173
|
+
if (col.defaultNow)
|
|
174
|
+
lines.push(`${t} SET DEFAULT CURRENT_TIMESTAMP;`);
|
|
175
|
+
}
|
|
176
|
+
// The primary key: renamed (its index follows); an app without one is not adoptable.
|
|
177
|
+
lines.push(doBlock(` SELECT conname INTO n FROM pg_constraint WHERE conrelid = '${q(table.name)}'::regclass AND contype = 'p';\n IF n IS NULL THEN RAISE EXCEPTION 'auth-sync adopt: ${table.name} has no primary key'; END IF;\n IF n <> '${table.name}_pkey' THEN EXECUTE format('ALTER TABLE %I RENAME CONSTRAINT %I TO %I', '${table.name}', n, '${table.name}_pkey'); END IF;`));
|
|
178
|
+
if (table.unique) {
|
|
179
|
+
lines.push(doBlock(` ${indexLookup(table.name, table.unique, true)}\n IF n IS NULL THEN RAISE EXCEPTION 'auth-sync adopt: ${table.name} has no unique index on ${table.unique}'; END IF;\n IF EXISTS (SELECT 1 FROM pg_constraint WHERE conrelid = '${q(table.name)}'::regclass AND conname = n AND contype = 'u') THEN\n -- Prisma's @unique is a unique index, not a constraint.\n EXECUTE format('ALTER TABLE %I DROP CONSTRAINT %I', '${table.name}', n);\n CREATE UNIQUE INDEX ${q(`${table.name}_${table.unique}_key`)} ON ${q(table.name)}(${q(table.unique)});\n ELSIF n <> '${table.name}_${table.unique}_key' THEN\n EXECUTE format('ALTER INDEX %I RENAME TO %I', n, '${table.name}_${table.unique}_key');\n END IF;`));
|
|
180
|
+
}
|
|
181
|
+
for (const column of table.indexes) {
|
|
182
|
+
const canonical = `${table.name}_${column}_idx`;
|
|
183
|
+
lines.push(doBlock(` ${indexLookup(table.name, column, false)}\n IF n IS NULL THEN\n CREATE INDEX ${q(canonical)} ON ${q(table.name)}(${q(column)});\n ELSIF n <> '${canonical}' THEN\n EXECUTE format('ALTER INDEX %I RENAME TO %I', n, '${canonical}');\n END IF;`));
|
|
184
|
+
}
|
|
185
|
+
if (table.foreignKey) {
|
|
186
|
+
const { column, references } = table.foreignKey;
|
|
187
|
+
lines.push(`ALTER TABLE ${q(table.name)} ADD CONSTRAINT ${q(`${table.name}_${column}_fkey`)} FOREIGN KEY (${q(column)}) REFERENCES ${q(references)}("id") ON DELETE CASCADE ON UPDATE CASCADE;`);
|
|
188
|
+
}
|
|
189
|
+
for (const [name, expression] of Object.entries(table.checks)) {
|
|
190
|
+
lines.push(`ALTER TABLE ${q(table.name)} ADD CONSTRAINT ${q(name)} CHECK (${expression});`);
|
|
191
|
+
}
|
|
192
|
+
out.push(`-- ${table.name}\n${lines.join("\n\n")}`);
|
|
193
|
+
}
|
|
194
|
+
return `${out.join("\n\n")}\n`;
|
|
195
|
+
}
|
|
196
|
+
/** PL/pgSQL assigning to `n` the name of the single-column index on `column` (a unique
|
|
197
|
+
* one, or a plain one), or NULL. */
|
|
198
|
+
function indexLookup(table, column, unique) {
|
|
199
|
+
return `SELECT c.relname INTO n FROM pg_index i JOIN pg_class c ON c.oid = i.indexrelid\n WHERE i.indrelid = '${q(table)}'::regclass AND i.indnatts = 1 AND NOT i.indisprimary AND i.indisunique = ${unique}\n AND i.indkey[0] = (SELECT attnum FROM pg_attribute WHERE attrelid = i.indrelid AND attname = '${column}')\n ORDER BY c.relname LIMIT 1;`;
|
|
200
|
+
}
|
|
201
|
+
//# sourceMappingURL=auth-adopt.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"auth-adopt.js","sourceRoot":"","sources":["../../src/cli/auth-adopt.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;GAmBG;AACH,OAAO,EAAE,YAAY,EAAE,MAAM,SAAS,CAAC;AACvC,OAAO,EAAE,kBAAkB,EAAE,MAAM,8BAA8B,CAAC;AAyBlE,MAAM,OAAO,GAAG,qBAAqB,CAAC;AACtC,MAAM,aAAa,GAAG,uBAAuB,CAAC;AAC9C,MAAM,SAAS,GAAG,wBAAwB,CAAC;AAG3C,MAAM,MAAM,GAAgB;IAC1B;QACE,IAAI,EAAE,OAAO;QACb,OAAO,EAAE;YACP,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,MAAM,EAAE;YAC5B,EAAE,IAAI,EAAE,SAAS,EAAE,IAAI,EAAE,MAAM,EAAE;YACjC,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,EAAE;YAC9B,EAAE,IAAI,EAAE,OAAO,EAAE,IAAI,EAAE,MAAM,EAAE;YAC/B,EAAE,IAAI,EAAE,kBAAkB,EAAE,IAAI,EAAE,MAAM,EAAE;YAC1C,EAAE,IAAI,EAAE,6BAA6B,EAAE,IAAI,EAAE,WAAW,EAAE;YAC1D,EAAE,IAAI,EAAE,mBAAmB,EAAE,IAAI,EAAE,MAAM,EAAE,QAAQ,EAAE,IAAI,EAAE;YAC3D,EAAE,IAAI,EAAE,UAAU,EAAE,IAAI,EAAE,MAAM,EA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A6E,MAAM,wGAAwG,MAAM,oCAAoC,CAAC;AAClW,CAAC"}
|
package/dist/cli/auth-sync.js
CHANGED
|
@@ -8,9 +8,10 @@
|
|
|
8
8
|
* fragment name and the "auth-sync" bin name; trace-sync.ts/profile-sync.ts are the
|
|
9
9
|
* same wrapper for the trace/profile fragments.
|
|
10
10
|
*/
|
|
11
|
+
import { buildAdoptSql, readAdoptMapping } from "./auth-adopt.js";
|
|
11
12
|
import { isRunningAsMain, runSyncCli, SyncCliError } from "./sync-engine.js";
|
|
12
13
|
export async function main(argv) {
|
|
13
|
-
return runSyncCli(argv, { name: "auth", binName: "auth-sync" });
|
|
14
|
+
return runSyncCli(argv, { name: "auth", binName: "auth-sync", prismaMigrateAware: true, adopt: (mapFile) => buildAdoptSql(readAdoptMapping(mapFile)) });
|
|
14
15
|
}
|
|
15
16
|
if (isRunningAsMain(import.meta.url)) {
|
|
16
17
|
main(process.argv.slice(2)).catch((err) => {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"auth-sync.js","sourceRoot":"","sources":["../../src/cli/auth-sync.ts"],"names":[],"mappings":";AACA;;;;;;;;GAQG;AACH,OAAO,EAAE,eAAe,EAAE,UAAU,EAAE,YAAY,EAAE,MAAM,kBAAkB,CAAC;AAE7E,MAAM,CAAC,KAAK,UAAU,IAAI,CAAC,IAAc;IACvC,OAAO,UAAU,CAAC,IAAI,EAAE,EAAE,IAAI,EAAE,MAAM,EAAE,OAAO,EAAE,WAAW,EAAE,CAAC,CAAC;
|
|
1
|
+
{"version":3,"file":"auth-sync.js","sourceRoot":"","sources":["../../src/cli/auth-sync.ts"],"names":[],"mappings":";AACA;;;;;;;;GAQG;AACH,OAAO,EAAE,aAAa,EAAE,gBAAgB,EAAE,MAAM,iBAAiB,CAAC;AAClE,OAAO,EAAE,eAAe,EAAE,UAAU,EAAE,YAAY,EAAE,MAAM,kBAAkB,CAAC;AAE7E,MAAM,CAAC,KAAK,UAAU,IAAI,CAAC,IAAc;IACvC,OAAO,UAAU,CAAC,IAAI,EAAE,EAAE,IAAI,EAAE,MAAM,EAAE,OAAO,EAAE,WAAW,EAAE,kBAAkB,EAAE,IAAI,EAAE,KAAK,EAAE,CAAC,OAAO,EAAE,EAAE,CAAC,aAAa,CAAC,gBAAgB,CAAC,OAAO,CAAC,CAAC,EAAE,CAAC,CAAC;AAC1J,CAAC;AAED,IAAI,eAAe,CAAC,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC;IACrC,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,GAAY,EAAE,EAAE;QACjD,IAAI,CAAC,CAAC,GAAG,YAAY,YAAY,CAAC,EAAE,CAAC;YACnC,OAAO,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;QACrB,CAAC;QACD,OAAO,CAAC,QAAQ,GAAG,OAAO,CAAC,QAAQ,IAAI,CAAC,CAAC;IAC3C,CAAC,CAAC,CAAC;AACL,CAAC"}
|
|
@@ -11,6 +11,14 @@ export interface SyncFragment {
|
|
|
11
11
|
name: string;
|
|
12
12
|
/** e.g. "trace-sync" or "profile-sync" — the bin name this is invoked as. */
|
|
13
13
|
binName: string;
|
|
14
|
+
/** In an app on Prisma migrate (`migration_lock.toml`), install the models only: write
|
|
15
|
+
* and run no SQL, and lock just the fragment checksum (AK-63). Set by the auth
|
|
16
|
+
* fragment; trace, profile and flags keep their raw-SQL install. */
|
|
17
|
+
prismaMigrateAware?: boolean;
|
|
18
|
+
/** Offers the `adopt` subcommand (AK-63) for a fragment whose tables apps already had
|
|
19
|
+
* before app-kit shipped them (auth): returns the migration SQL for the mapping file
|
|
20
|
+
* at the given path, throwing an Error that names what is wrong with it. */
|
|
21
|
+
adopt?: (mapFile: string) => string;
|
|
14
22
|
}
|
|
15
23
|
export declare class SyncCliError extends Error {
|
|
16
24
|
}
|
package/dist/cli/sync-engine.js
CHANGED
|
@@ -35,7 +35,14 @@
|
|
|
35
35
|
* the manifest down to `entry.fragment === fragment.name` before doing anything, so
|
|
36
36
|
* e.g. `trace-sync init` only ever touches trace's own migrations, never profile's.
|
|
37
37
|
*
|
|
38
|
-
*
|
|
38
|
+
* For a fragment marked `prismaMigrateAware` (auth), an app that uses Prisma migrate
|
|
39
|
+
* (its prisma/migrations holds `migration_lock.toml`) gets none of that raw SQL (AK-63): copying a package migration into prisma/migrations
|
|
40
|
+
* makes `prisma migrate deploy` run it, ahead of the app's own migrations, and running
|
|
41
|
+
* it directly against DATABASE_URL bypasses the app's deploy. There the CLI only
|
|
42
|
+
* installs the fragment's models; the app's own `prisma migrate dev` creates the
|
|
43
|
+
* migration, and the lock records just the fragment checksum.
|
|
44
|
+
*
|
|
45
|
+
* Subcommands (identical across every fragment, plus `adopt` for the auth fragment):
|
|
39
46
|
* <bin> init copy fragment + migrations in, run `prisma validate` and
|
|
40
47
|
* `prisma db execute`, write the lock file.
|
|
41
48
|
* <bin> diff read-only: compare this package's bundled fragment version /
|
|
@@ -44,6 +51,9 @@
|
|
|
44
51
|
* <bin> apply apply pending migrations + refresh the fragment copy, update the
|
|
45
52
|
* lock file. Does not re-run `prisma validate` against a fresh
|
|
46
53
|
* init — use `init` for first install.
|
|
54
|
+
* <bin> adopt --map=<file> (auth only, Prisma migrate apps) write a Prisma migration
|
|
55
|
+
* that renames the app's existing auth tables to the fragment's
|
|
56
|
+
* (see auth-adopt.ts). Writes the file; executes nothing.
|
|
47
57
|
* <bin> status read-only report: fragment version, applied migrations, and
|
|
48
58
|
* whether the consumer's copy of the fragment has been hand-edited
|
|
49
59
|
* (checksum mismatch).
|
|
@@ -53,7 +63,7 @@
|
|
|
53
63
|
*/
|
|
54
64
|
import { createHash } from "node:crypto";
|
|
55
65
|
import spawn from "cross-spawn";
|
|
56
|
-
import { copyFileSync, cpSync, existsSync, mkdirSync, readFileSync, writeFileSync, } from "node:fs";
|
|
66
|
+
import { copyFileSync, cpSync, existsSync, mkdirSync, readdirSync, readFileSync, writeFileSync, } from "node:fs";
|
|
57
67
|
import path from "node:path";
|
|
58
68
|
import { fileURLToPath, pathToFileURL } from "node:url";
|
|
59
69
|
// Re-exported so trace-sync.ts/profile-sync.ts/flags-sync.ts keep importing it from
|
|
@@ -114,11 +124,16 @@ class SyncEngine {
|
|
|
114
124
|
lockFilePath(consumerRoot) {
|
|
115
125
|
return path.join(consumerRoot, this.lockFileName);
|
|
116
126
|
}
|
|
117
|
-
readLockFile(consumerRoot) {
|
|
127
|
+
readLockFile(consumerRoot, migrate) {
|
|
118
128
|
const p = this.lockFilePath(consumerRoot);
|
|
119
129
|
if (!existsSync(p))
|
|
120
130
|
return null;
|
|
121
|
-
|
|
131
|
+
const lock = readJson(p);
|
|
132
|
+
if ("appliedMigrations" in lock === migrate) {
|
|
133
|
+
this.fail(`${this.lockFileName} was written for an app ${migrate ? "without" : "with"} Prisma migrate, ` +
|
|
134
|
+
`and this app ${migrate ? "uses" : "does not use"} it. Run "${this.fragment.binName} init" to rewrite it.`);
|
|
135
|
+
}
|
|
136
|
+
return lock;
|
|
122
137
|
}
|
|
123
138
|
writeLockFile(consumerRoot, lock) {
|
|
124
139
|
writeFileSync(this.lockFilePath(consumerRoot), `${JSON.stringify(lock, null, 2)}\n`, "utf8");
|
|
@@ -200,6 +215,25 @@ class SyncEngine {
|
|
|
200
215
|
prismaRoot: this.resolvePrismaRoot(schemaPath),
|
|
201
216
|
};
|
|
202
217
|
}
|
|
218
|
+
/** True for a Prisma-migrate-aware fragment in an app on Prisma migrate: it keeps `migration_lock.toml` in its migrations. */
|
|
219
|
+
usesPrismaMigrate(layout) {
|
|
220
|
+
return (this.fragment.prismaMigrateAware === true &&
|
|
221
|
+
existsSync(path.join(layout.prismaRoot, "migrations", "migration_lock.toml")));
|
|
222
|
+
}
|
|
223
|
+
/** What to tell an app on Prisma migrate once the fragment's models are in its schema. */
|
|
224
|
+
printMigrateNextSteps() {
|
|
225
|
+
const bin = this.fragment.binName;
|
|
226
|
+
console.log(`${bin}: this app uses Prisma migrate, so no SQL was written or run. ` +
|
|
227
|
+
`Create the tables with "npx prisma migrate dev --create-only".`);
|
|
228
|
+
const checks = this.readManifest()
|
|
229
|
+
.flatMap((entry) => readFileSync(path.join(this.migrationsSrcDir, entry.file), "utf8").match(/^ALTER TABLE .* ADD CONSTRAINT .* CHECK .*;$/gm) ?? []);
|
|
230
|
+
if (checks.length > 0) {
|
|
231
|
+
console.log(`${bin}: Prisma's schema language has no CHECK, so append these to the generated migration.sql before you apply it:\n${checks.join("\n")}`);
|
|
232
|
+
}
|
|
233
|
+
if (this.fragment.adopt) {
|
|
234
|
+
console.log(`${bin}: if the app already has these tables, run "${bin} adopt --map=<file>" instead of creating them.`);
|
|
235
|
+
}
|
|
236
|
+
}
|
|
203
237
|
/** The conventional "prisma root" a schema folder sits under, used to locate (or
|
|
204
238
|
* create) the sibling `migrations/` directory. For the common multi-file layout
|
|
205
239
|
* `prisma/schema/*.prisma`, that's `prisma/`. */
|
|
@@ -459,6 +493,12 @@ class SyncEngine {
|
|
|
459
493
|
this.installFragment(layout, schemaNameOverride);
|
|
460
494
|
console.log(`${bin}: running "npx prisma validate" against ${consumerRoot}`);
|
|
461
495
|
this.runPrisma(["validate"], consumerRoot);
|
|
496
|
+
if (this.usesPrismaMigrate(layout)) {
|
|
497
|
+
this.writeMigrateLock(consumerRoot, layout);
|
|
498
|
+
this.printMigrateNextSteps();
|
|
499
|
+
console.log(`${bin}: init complete.`);
|
|
500
|
+
return;
|
|
501
|
+
}
|
|
462
502
|
const manifest = this.readManifest();
|
|
463
503
|
const appliedMigrations = [];
|
|
464
504
|
for (const entry of manifest) {
|
|
@@ -486,11 +526,26 @@ class SyncEngine {
|
|
|
486
526
|
console.log(`${bin}: wrote ${this.lockFilePath(consumerRoot)}`);
|
|
487
527
|
console.log(`${bin}: init complete.`);
|
|
488
528
|
}
|
|
489
|
-
|
|
490
|
-
|
|
529
|
+
writeMigrateLock(consumerRoot, layout) {
|
|
530
|
+
this.writeLockFile(consumerRoot, {
|
|
531
|
+
fragmentVersion: this.readFragmentMeta().fragmentVersion,
|
|
532
|
+
fragmentChecksum: this.computeFragmentChecksum(layout),
|
|
533
|
+
lastSyncedAt: new Date().toISOString(),
|
|
534
|
+
});
|
|
535
|
+
console.log(`${this.fragment.binName}: wrote ${this.lockFilePath(consumerRoot)}`);
|
|
536
|
+
}
|
|
537
|
+
requireLock(consumerRoot, migrate) {
|
|
538
|
+
const lock = migrate ? this.readLockFile(consumerRoot, true) : this.readLockFile(consumerRoot, false);
|
|
491
539
|
if (!lock) {
|
|
492
540
|
this.fail(`no ${this.lockFileName} found at ${consumerRoot}. Run "${this.fragment.binName} init" first.`);
|
|
493
541
|
}
|
|
542
|
+
return lock;
|
|
543
|
+
}
|
|
544
|
+
async usesMigrate(consumerRoot) {
|
|
545
|
+
const layout = this.classifySchemaLayout(await this.loadConsumerSchemaPath(consumerRoot));
|
|
546
|
+
return this.usesPrismaMigrate(layout);
|
|
547
|
+
}
|
|
548
|
+
computePending(lock) {
|
|
494
549
|
const meta = this.readFragmentMeta();
|
|
495
550
|
const manifest = this.readManifest();
|
|
496
551
|
const applied = new Set(lock.appliedMigrations);
|
|
@@ -502,8 +557,17 @@ class SyncEngine {
|
|
|
502
557
|
pendingMigrations,
|
|
503
558
|
};
|
|
504
559
|
}
|
|
505
|
-
cmdDiff(consumerRoot) {
|
|
506
|
-
|
|
560
|
+
async cmdDiff(consumerRoot) {
|
|
561
|
+
if (await this.usesMigrate(consumerRoot)) {
|
|
562
|
+
const lock = this.requireLock(consumerRoot, true);
|
|
563
|
+
const current = this.readFragmentMeta().fragmentVersion;
|
|
564
|
+
console.log(lock.fragmentVersion === current
|
|
565
|
+
? `fragment version: ${current} (up to date)`
|
|
566
|
+
: `fragment version: ${lock.fragmentVersion} -> ${current} (changed)`);
|
|
567
|
+
console.log("migrations: none (Prisma migrate app: create them with prisma migrate dev).");
|
|
568
|
+
return;
|
|
569
|
+
}
|
|
570
|
+
const report = this.computePending(this.requireLock(consumerRoot, false));
|
|
507
571
|
if (report.fragmentVersionChanged) {
|
|
508
572
|
console.log(`fragment version: ${report.fragmentVersionInstalled} -> ${report.fragmentVersionCurrent} (changed)`);
|
|
509
573
|
}
|
|
@@ -522,15 +586,19 @@ class SyncEngine {
|
|
|
522
586
|
}
|
|
523
587
|
async cmdApply(consumerRoot, schemaNameOverride) {
|
|
524
588
|
const bin = this.fragment.binName;
|
|
525
|
-
const report = this.computePending(consumerRoot);
|
|
526
589
|
const schemaPath = await this.loadConsumerSchemaPath(consumerRoot);
|
|
527
590
|
const layout = this.classifySchemaLayout(schemaPath);
|
|
528
591
|
const migrationsDestDir = path.join(layout.prismaRoot, "migrations");
|
|
529
|
-
this.
|
|
530
|
-
|
|
531
|
-
|
|
532
|
-
this.
|
|
592
|
+
if (this.usesPrismaMigrate(layout)) {
|
|
593
|
+
this.requireLock(consumerRoot, true);
|
|
594
|
+
this.installFragment(layout, schemaNameOverride);
|
|
595
|
+
this.writeMigrateLock(consumerRoot, layout);
|
|
596
|
+
console.log(`${bin}: apply complete (Prisma migrate app: models refreshed, no SQL run).`);
|
|
597
|
+
return;
|
|
533
598
|
}
|
|
599
|
+
const lock = this.requireLock(consumerRoot, false);
|
|
600
|
+
const report = this.computePending(lock);
|
|
601
|
+
this.installFragment(layout, schemaNameOverride);
|
|
534
602
|
const appliedMigrations = [...lock.appliedMigrations];
|
|
535
603
|
if (report.pendingMigrations.length === 0) {
|
|
536
604
|
console.log(`${bin}: no pending migrations to apply.`);
|
|
@@ -556,18 +624,66 @@ class SyncEngine {
|
|
|
556
624
|
console.log(`${bin}: wrote ${this.lockFilePath(consumerRoot)}`);
|
|
557
625
|
console.log(`${bin}: apply complete.`);
|
|
558
626
|
}
|
|
627
|
+
/**
|
|
628
|
+
* Writes the Prisma migration that renames the app's existing tables to the fragment's
|
|
629
|
+
* (see auth-adopt.ts) as `prisma/migrations/<UTC timestamp>_adopt_app_kit_<fragment>_fragment/`.
|
|
630
|
+
* Executes nothing; the app's `prisma migrate deploy` applies it.
|
|
631
|
+
*/
|
|
632
|
+
async cmdAdopt(consumerRoot, mapFile) {
|
|
633
|
+
const bin = this.fragment.binName;
|
|
634
|
+
const adopt = this.fragment.adopt;
|
|
635
|
+
if (!adopt) {
|
|
636
|
+
this.fail(`the ${this.fragment.name} fragment has no adopt path.`);
|
|
637
|
+
}
|
|
638
|
+
if (!mapFile) {
|
|
639
|
+
this.fail(`adopt needs --map=<file>: JSON naming your existing tables, e.g. ` +
|
|
640
|
+
`{"tables": {"app_kit_idp_session": "sessions", "app_kit_refresh_token": "refresh_tokens", ` +
|
|
641
|
+
`"app_kit_auth_audit_log": "auth_audit_logs"}, "columns": {"app_kit_refresh_token": {"idp_session_id": "session_id"}}} ` +
|
|
642
|
+
`(columns only where your name differs from the fragment's).`);
|
|
643
|
+
}
|
|
644
|
+
const layout = this.classifySchemaLayout(await this.loadConsumerSchemaPath(consumerRoot));
|
|
645
|
+
if (!this.usesPrismaMigrate(layout)) {
|
|
646
|
+
this.fail(`adopt writes a Prisma migration, and ${path.join(layout.prismaRoot, "migrations", "migration_lock.toml")} ` +
|
|
647
|
+
`does not exist: this app does not use Prisma migrate.`);
|
|
648
|
+
}
|
|
649
|
+
let sql;
|
|
650
|
+
try {
|
|
651
|
+
sql = adopt(path.resolve(consumerRoot, mapFile));
|
|
652
|
+
}
|
|
653
|
+
catch (err) {
|
|
654
|
+
this.fail(err.message);
|
|
655
|
+
}
|
|
656
|
+
const migrationsDir = path.join(layout.prismaRoot, "migrations");
|
|
657
|
+
const stamp = new Date().toISOString().replace(/\D/g, "").slice(0, 14);
|
|
658
|
+
const name = `${stamp}_adopt_app_kit_${this.fragment.name}_fragment`;
|
|
659
|
+
const later = readdirSync(migrationsDir).filter((entry) => /^\d{14}_/.test(entry) && entry.slice(0, 14) > stamp);
|
|
660
|
+
if (later.length > 0) {
|
|
661
|
+
this.fail(`${later[0]} is dated after now (${stamp}); adopt must be the newest migration.`);
|
|
662
|
+
}
|
|
663
|
+
mkdirSync(path.join(migrationsDir, name));
|
|
664
|
+
writeFileSync(path.join(migrationsDir, name, "migration.sql"), sql, "utf8");
|
|
665
|
+
console.log(`${bin}: wrote ${path.join(migrationsDir, name, "migration.sql")}`);
|
|
666
|
+
console.log(`${bin}: replace your own auth models with the fragment's ("${bin} init"), then "npx prisma migrate deploy" applies it.`);
|
|
667
|
+
}
|
|
559
668
|
async cmdStatus(consumerRoot) {
|
|
560
|
-
|
|
561
|
-
if (!lock) {
|
|
669
|
+
if (!existsSync(this.lockFilePath(consumerRoot))) {
|
|
562
670
|
console.log(`no ${this.lockFileName} found at ${consumerRoot}. Not yet initialized — run "${this.fragment.binName} init".`);
|
|
563
671
|
return;
|
|
564
672
|
}
|
|
673
|
+
const migrate = await this.usesMigrate(consumerRoot);
|
|
674
|
+
const rawLock = migrate ? null : this.requireLock(consumerRoot, false);
|
|
675
|
+
const lock = rawLock ?? this.requireLock(consumerRoot, true);
|
|
565
676
|
console.log(`fragment version (installed): ${lock.fragmentVersion}`);
|
|
566
677
|
console.log(`fragment version (package): ${this.readFragmentMeta().fragmentVersion}`);
|
|
567
678
|
console.log(`last synced: ${lock.lastSyncedAt}`);
|
|
568
|
-
|
|
569
|
-
|
|
570
|
-
|
|
679
|
+
if (rawLock === null) {
|
|
680
|
+
console.log("applied migrations: none (Prisma migrate app)");
|
|
681
|
+
}
|
|
682
|
+
else {
|
|
683
|
+
console.log(`applied migrations (${rawLock.appliedMigrations.length}):`);
|
|
684
|
+
for (const id of rawLock.appliedMigrations) {
|
|
685
|
+
console.log(` - ${id}`);
|
|
686
|
+
}
|
|
571
687
|
}
|
|
572
688
|
try {
|
|
573
689
|
const schemaPath = await this.loadConsumerSchemaPath(consumerRoot);
|
|
@@ -612,7 +728,7 @@ class SyncEngine {
|
|
|
612
728
|
// ---------------------------------------------------------------------------
|
|
613
729
|
// Entry point shared by every fragment's bin wrapper
|
|
614
730
|
// ---------------------------------------------------------------------------
|
|
615
|
-
const SUBCOMMANDS = ["init", "diff", "apply", "status"];
|
|
731
|
+
const SUBCOMMANDS = ["init", "diff", "apply", "status", "adopt"];
|
|
616
732
|
function isSubcommand(value) {
|
|
617
733
|
return SUBCOMMANDS.includes(value);
|
|
618
734
|
}
|
|
@@ -640,6 +756,21 @@ function parseSchemaNameFlag(rest) {
|
|
|
640
756
|
}
|
|
641
757
|
return undefined;
|
|
642
758
|
}
|
|
759
|
+
/** Parses `--map=<file>` / `--map <file>`, the mapping `adopt` reads. */
|
|
760
|
+
function parseMapFlag(rest) {
|
|
761
|
+
for (let i = 0; i < rest.length; i++) {
|
|
762
|
+
const arg = rest[i];
|
|
763
|
+
if (arg === "--map") {
|
|
764
|
+
const value = rest[i + 1];
|
|
765
|
+
if (value === undefined)
|
|
766
|
+
throw new SyncCliError("--map requires a value, e.g. --map=adopt.json");
|
|
767
|
+
return value;
|
|
768
|
+
}
|
|
769
|
+
if (arg.startsWith("--map="))
|
|
770
|
+
return arg.slice("--map=".length);
|
|
771
|
+
}
|
|
772
|
+
return undefined;
|
|
773
|
+
}
|
|
643
774
|
/**
|
|
644
775
|
* Runs one CLI invocation for the given fragment. Called by each bin wrapper
|
|
645
776
|
* (src/cli/trace-sync.ts, src/cli/profile-sync.ts) with `process.argv.slice(2)`.
|
|
@@ -647,7 +778,7 @@ function parseSchemaNameFlag(rest) {
|
|
|
647
778
|
export async function runSyncCli(argv, fragment) {
|
|
648
779
|
const [subcommand, ...rest] = argv;
|
|
649
780
|
if (!isSubcommand(subcommand)) {
|
|
650
|
-
console.error(`usage: ${fragment.binName} <${SUBCOMMANDS.join("|")}> [--schema-name=<name>]`);
|
|
781
|
+
console.error(`usage: ${fragment.binName} <${SUBCOMMANDS.filter((c) => c !== "adopt" || fragment.adopt).join("|")}> [--schema-name=<name>]`);
|
|
651
782
|
process.exitCode = 1;
|
|
652
783
|
return;
|
|
653
784
|
}
|
|
@@ -659,7 +790,7 @@ export async function runSyncCli(argv, fragment) {
|
|
|
659
790
|
await engine.cmdInit(consumerRoot, schemaNameOverride);
|
|
660
791
|
break;
|
|
661
792
|
case "diff":
|
|
662
|
-
engine.cmdDiff(consumerRoot);
|
|
793
|
+
await engine.cmdDiff(consumerRoot);
|
|
663
794
|
break;
|
|
664
795
|
case "apply":
|
|
665
796
|
await engine.cmdApply(consumerRoot, schemaNameOverride);
|
|
@@ -667,6 +798,9 @@ export async function runSyncCli(argv, fragment) {
|
|
|
667
798
|
case "status":
|
|
668
799
|
await engine.cmdStatus(consumerRoot);
|
|
669
800
|
break;
|
|
801
|
+
case "adopt":
|
|
802
|
+
await engine.cmdAdopt(consumerRoot, parseMapFlag(rest));
|
|
803
|
+
break;
|
|
670
804
|
}
|
|
671
805
|
}
|
|
672
806
|
//# sourceMappingURL=sync-engine.js.map
|