@uncutsql/core 0.8.0 → 0.9.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/index.cjs CHANGED
@@ -200,6 +200,35 @@ var SchemaDiffError = class extends effect.Data.TaggedError("SchemaDiffError") {
200
200
  return this.diagnostics.map((item) => `${item.side}: ${item.message}`).join("\n");
201
201
  }
202
202
  };
203
+ /**
204
+ * Every column a table change carries over: changed, renamed and unchanged ones. A table option
205
+ * can change how a column with an unchanged declaration stores values (SQLite `STRICT`), so the
206
+ * dialect classifies every pair, not only declaration changes (ADR 0042).
207
+ */
208
+ const pairedColumns = (before, after, changes) => {
209
+ const pairs = [];
210
+ const touchedBefore = /* @__PURE__ */ new Set();
211
+ const touchedAfter = /* @__PURE__ */ new Set();
212
+ for (const change of changes) if (change._tag === "ColumnChanged" || change._tag === "ColumnRenamed") {
213
+ pairs.push({
214
+ after: change.after,
215
+ before: change.before,
216
+ renamed: change._tag === "ColumnRenamed"
217
+ });
218
+ touchedBefore.add(change.before.key);
219
+ touchedAfter.add(change.after.key);
220
+ } else if (change._tag === "ColumnAdded") touchedAfter.add(change.column.key);
221
+ else if (change._tag === "ColumnRemoved") touchedBefore.add(change.column.key);
222
+ for (const column of after.columns) {
223
+ const source = touchedAfter.has(column.key) ? void 0 : before.columns.find((item) => item.key === column.key && !touchedBefore.has(item.key));
224
+ if (source) pairs.push({
225
+ after: column,
226
+ before: source,
227
+ renamed: false
228
+ });
229
+ }
230
+ return pairs;
231
+ };
203
232
  const validateDatabase = (database, side) => {
204
233
  const diagnostics = [];
205
234
  const tables = /* @__PURE__ */ new Set();
@@ -1026,6 +1055,7 @@ const diffDatabases = (before, after) => effect.Effect.gen(function* () {
1026
1055
  /** Low-level logical lowering of caller-approved intent. Resolve migration decisions first in user-facing workflows. */
1027
1056
  const planDatabaseMigration = (diff) => ({
1028
1057
  ...diff.dropGuards ? { dropGuards: diff.dropGuards } : {},
1058
+ ...diff.typeChanges ? { typeChanges: diff.typeChanges } : {},
1029
1059
  procedures: diff.changes.map((change) => {
1030
1060
  switch (change._tag) {
1031
1061
  case "NamespaceAdded":
@@ -1851,6 +1881,7 @@ const nextMigration = (run, migrations, tipId) => run.baseline && tipId === 0 ?
1851
1881
  var MigrationDecisionError = class extends effect.Data.TaggedError("MigrationDecisionError") {};
1852
1882
  const equal = (a, b) => schemaValueEqual(a, b);
1853
1883
  const record = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
1884
+ const isJson = effect.Schema.is(effect.Schema.Json);
1854
1885
  const idFor = (table, column) => JSON.stringify([tableKey(table), column ?? null]);
1855
1886
  const renamedColumnId = (source, target, column) => JSON.stringify([
1856
1887
  tableKey(source),
@@ -1865,12 +1896,103 @@ const valueId = (source, target, value) => JSON.stringify([
1865
1896
  tableKey(target),
1866
1897
  value
1867
1898
  ]);
1868
- const enumLabel = (identity) => [
1899
+ const qualifiedName = (identity) => [
1869
1900
  identity.catalog,
1870
1901
  identity.schema,
1871
1902
  identity.name
1872
1903
  ].filter((part) => part !== void 0).join(".");
1873
1904
  const quoted = (value) => `'${JSON.stringify(value).slice(1, -1)}'`;
1905
+ const isTypeChangeKind = (kind) => kind === "type_change_loss" || kind === "type_change_failure";
1906
+ const typeChangeId = (kind, change, support) => {
1907
+ const { source, target } = support.displayTypes(change);
1908
+ return JSON.stringify([
1909
+ kind,
1910
+ tableKey(change.before.table.identity),
1911
+ tableKey(change.after.table.identity),
1912
+ change.before.column.key,
1913
+ change.after.column.key,
1914
+ source,
1915
+ target
1916
+ ]);
1917
+ };
1918
+ const typeChangePair = (document, id, kind, support, renames) => {
1919
+ if (!isTypeChangeKind(kind)) return;
1920
+ let parts;
1921
+ try {
1922
+ parts = JSON.parse(id);
1923
+ } catch {
1924
+ return;
1925
+ }
1926
+ if (!Array.isArray(parts) || parts.length !== 7 || parts[0] !== kind) return;
1927
+ const [, source, target, sourceColumn, targetColumn] = parts;
1928
+ const side = (schema, tableId, columnKey) => {
1929
+ const table = schema.tables.find((item) => tableKey(item.identity) === tableId);
1930
+ const column = table?.columns.find((item) => item.key === columnKey);
1931
+ return table && column ? {
1932
+ column,
1933
+ schema,
1934
+ table
1935
+ } : void 0;
1936
+ };
1937
+ const before = side(document.before, source, sourceColumn);
1938
+ const after = side(document.after, target, targetColumn);
1939
+ if (before && after && id === typeChangeId(kind, {
1940
+ after,
1941
+ before
1942
+ }, support)) return {
1943
+ after,
1944
+ before,
1945
+ ...renames ? { enumRenames: renames } : {}
1946
+ };
1947
+ };
1948
+ const validateFallback = (document, decision, literal, typeChange, renames) => {
1949
+ const pair = typeChangePair(document, decision.id, decision.kind, typeChange, renames);
1950
+ return pair ? typeChange.validateFallback(pair, literal) : "The type-change decision does not identify a column pair in the snapshots.";
1951
+ };
1952
+ const typeChangeReviews = (diff, schemas, support, scope, renames) => {
1953
+ if (!support) return [];
1954
+ const reviews = [];
1955
+ for (const table of diff.changes) {
1956
+ if (!("changes" in table)) continue;
1957
+ for (const column of pairedColumns(table.before, table.after, table.changes)) {
1958
+ if (scope !== "all" && scope === "nested" !== (table._tag === "TableRenamed" || column.renamed)) continue;
1959
+ const change = {
1960
+ after: {
1961
+ column: column.after,
1962
+ schema: schemas.after,
1963
+ table: table.after
1964
+ },
1965
+ before: {
1966
+ column: column.before,
1967
+ schema: schemas.before,
1968
+ table: table.before
1969
+ },
1970
+ ...renames ? { enumRenames: renames } : {}
1971
+ };
1972
+ const classification = support.classify(change);
1973
+ if (classification === void 0 || classification === "lossless") continue;
1974
+ const { source, target } = support.displayTypes(change);
1975
+ const label = `${qualifiedName(table.after.identity)}.${column.after.name}`;
1976
+ const question = (kind, text) => ({
1977
+ column: column.before.key,
1978
+ id: typeChangeId(kind, change, support),
1979
+ kind,
1980
+ question: text,
1981
+ resolution: { action: "pending" },
1982
+ table: table.before.identity
1983
+ });
1984
+ const questions = [];
1985
+ if (classification !== "may_lose") questions.push(question("type_change_failure", `How should the migration handle values that cannot convert when changing ${label} from ${source} to ${target}?`));
1986
+ if (classification !== "may_fail") questions.push(question("type_change_loss", `How should the migration handle values that would lose information when converting ${label} from ${source} to ${target}?`));
1987
+ reviews.push({
1988
+ change,
1989
+ classification,
1990
+ questions
1991
+ });
1992
+ }
1993
+ }
1994
+ return reviews;
1995
+ };
1874
1996
  const missingFrom = (values, other) => {
1875
1997
  const present = new Set(other);
1876
1998
  return values.filter((value) => !present.has(value));
@@ -1884,7 +2006,7 @@ const enumQuestions = (change, diff) => {
1884
2006
  candidates,
1885
2007
  enum: identity,
1886
2008
  id: enumId(identity),
1887
- question: `Drop type ${enumLabel(identity)}, or rename it to an added type?`,
2009
+ question: `Drop type ${qualifiedName(identity)}, or rename it to an added type?`,
1888
2010
  resolution: { action: "pending" }
1889
2011
  }] : [];
1890
2012
  }
@@ -1894,7 +2016,7 @@ const enumQuestions = (change, diff) => {
1894
2016
  candidates,
1895
2017
  enum: before.identity,
1896
2018
  id: valueId(before.identity, after.identity, value),
1897
- question: `Rename value ${quoted(value)} of ${enumLabel(before.identity)} to an added value?`,
2019
+ question: `Rename value ${quoted(value)} of ${qualifiedName(before.identity)} to an added value?`,
1898
2020
  resolution: { action: "pending" },
1899
2021
  value
1900
2022
  })) : [];
@@ -1922,13 +2044,27 @@ const questions = (diff) => diff.changes.flatMap((change) => {
1922
2044
  table: change.table
1923
2045
  }));
1924
2046
  });
1925
- const prepareMigrationDecisions = (before, after) => effect.Effect.map(diffDatabases(before, after), (diff) => ({
1926
- after,
1927
- before,
1928
- decisions: questions(diff),
1929
- version: 1
1930
- }));
1931
- const readAnswers = (pending, inputs, allowPending) => effect.Effect.gen(function* () {
2047
+ const defersTypeChanges = (decisions) => decisions.some((item) => "enum" in item && item.candidates.length > 0);
2048
+ const rootReview = (diff, before, after, typeChange) => {
2049
+ const removals = questions(diff);
2050
+ const typeChanges = defersTypeChanges(removals) ? [] : typeChangeReviews(diff, {
2051
+ after,
2052
+ before
2053
+ }, typeChange, "root");
2054
+ return {
2055
+ document: {
2056
+ after,
2057
+ before,
2058
+ decisions: [...removals, ...typeChanges.flatMap((review) => review.questions)],
2059
+ version: 1
2060
+ },
2061
+ typeChanges
2062
+ };
2063
+ };
2064
+ function prepareMigrationDecisions(before, after, typeChange) {
2065
+ return effect.Effect.map(diffDatabases(before, after), (diff) => rootReview(diff, before, after, typeChange).document);
2066
+ }
2067
+ const readAnswers = (pending, inputs, allowPending, typeChange, renames) => effect.Effect.gen(function* () {
1932
2068
  const fail = (message) => effect.Effect.fail(new MigrationDecisionError({
1933
2069
  message,
1934
2070
  pending
@@ -1940,13 +2076,37 @@ const readAnswers = (pending, inputs, allowPending) => effect.Effect.gen(functio
1940
2076
  if (!record(input) || typeof input.id !== "string") return yield* fail("Each decision needs its original id.");
1941
2077
  const question = expected.get(input.id);
1942
2078
  if (!question || answers.has(input.id)) return yield* fail(`Unknown or duplicate decision: ${input.id}`);
1943
- if (!("enum" in question ? input.table === void 0 && input.column === void 0 && equal(input.enum, question.enum) && input.value === question.value : input.enum === void 0 && input.value === void 0 && equal(input.table, question.table) && input.column === question.column)) return yield* fail(`Decision identity changed: ${input.id}`);
2079
+ if (!("enum" in question ? input.table === void 0 && input.column === void 0 && equal(input.enum, question.enum) && input.value === question.value : input.enum === void 0 && input.value === void 0 && equal(input.table, question.table) && input.column === question.column) || "kind" in question && input.kind !== question.kind) return yield* fail(`Decision identity changed: ${input.id}`);
1944
2080
  const resolution = input.resolution;
1945
2081
  if (allowPending && record(resolution) && resolution.action === "pending" && Object.keys(resolution).length === 1) {
1946
2082
  answers.set(input.id, question);
1947
2083
  continue;
1948
2084
  }
1949
2085
  if (!record(resolution) || resolution.action === "pending") return yield* fail(`Unresolved decision: ${question.question}`);
2086
+ if ("kind" in question) {
2087
+ const action = resolution.action;
2088
+ if (Object.keys(resolution).length === 1 && ((action === "accept_loss" || action === "guard") && question.kind === "type_change_loss" || action === "accept_failure" && question.kind === "type_change_failure")) {
2089
+ answers.set(input.id, {
2090
+ ...question,
2091
+ resolution: { action }
2092
+ });
2093
+ continue;
2094
+ }
2095
+ const fallback = resolution.fallback;
2096
+ if (question.kind === "type_change_failure" && Object.keys(resolution).length === 1 && record(fallback) && Object.keys(fallback).length === 1 && isJson(fallback.literal)) {
2097
+ const literal = fallback.literal;
2098
+ if (!allowPending && typeChange) {
2099
+ const reason = validateFallback(pending, question, literal, typeChange, renames);
2100
+ if (reason !== void 0) return yield* fail(`Invalid fallback for ${question.question} ${quoted(reason)}`);
2101
+ }
2102
+ answers.set(input.id, {
2103
+ ...question,
2104
+ resolution: { fallback: { literal } }
2105
+ });
2106
+ continue;
2107
+ }
2108
+ return yield* fail(`Invalid resolution for ${question.question}`);
2109
+ }
1950
2110
  if ((resolution.action === "drop" || resolution.action === "drop_if_empty" && !("enum" in question)) && Object.keys(resolution).length === 1) answers.set(input.id, {
1951
2111
  ...question,
1952
2112
  resolution: { action: resolution.action }
@@ -1970,7 +2130,7 @@ const readAnswers = (pending, inputs, allowPending) => effect.Effect.gen(functio
1970
2130
  });
1971
2131
  } else return yield* fail(`Invalid resolution for ${question.question}`);
1972
2132
  }
1973
- if (answers.size !== expected.size) return yield* fail("Missing migration decisions: every removal requires an explicit resolution.");
2133
+ if (answers.size !== expected.size) return yield* fail(pending.decisions.some((item) => "kind" in item && !answers.has(item.id)) ? "Missing migration decisions: every type-change question requires an explicit resolution." : "Missing migration decisions: every removal requires an explicit resolution.");
1974
2134
  return answers;
1975
2135
  });
1976
2136
  const expandRenames = (diff, answers) => {
@@ -2014,7 +2174,47 @@ const expandRenames = (diff, answers) => {
2014
2174
  nested: questions({ changes: renames })
2015
2175
  };
2016
2176
  };
2177
+ const pairColumns = (diff, resolutionFor) => ({ changes: diff.changes.map((change) => {
2178
+ if (!("changes" in change)) return change;
2179
+ const renamedSources = /* @__PURE__ */ new Set();
2180
+ const renamedTargets = /* @__PURE__ */ new Set();
2181
+ const renames = [];
2182
+ for (const item of change.changes) {
2183
+ if (item._tag !== "ColumnRemoved") continue;
2184
+ const resolution = resolutionFor(columnId(change, item.column.key));
2185
+ if (!record(resolution) || resolution.action !== "rename") continue;
2186
+ const target = change.changes.find((candidate) => candidate._tag === "ColumnAdded" && candidate.column.key === resolution.target);
2187
+ if (target?._tag !== "ColumnAdded") continue;
2188
+ renamedSources.add(item.column.key);
2189
+ renamedTargets.add(target.column.key);
2190
+ const fields = [];
2191
+ if (!equal(item.column.dataType, target.column.dataType)) fields.push("dataType");
2192
+ if (!constraintsEqual(item.column.constraints, target.column.constraints)) fields.push("constraints");
2193
+ renames.push({
2194
+ _tag: "ColumnRenamed",
2195
+ after: target.column,
2196
+ before: item.column,
2197
+ fields
2198
+ });
2199
+ }
2200
+ return {
2201
+ ...change,
2202
+ changes: [...renames, ...change.changes.filter((item) => !(item._tag === "ColumnAdded" && renamedTargets.has(item.column.key)) && !(item._tag === "ColumnRemoved" && renamedSources.has(item.column.key)))]
2203
+ };
2204
+ }) });
2205
+ const issuedForTypeChangePairing = (pending, input, deferred, typeChange) => {
2206
+ const pair = typeof input.id === "string" && typeChangePair(pending, input.id, input.kind, typeChange);
2207
+ if (!pair || !equal(input.table, pair.before.table.identity) || input.column !== pair.before.column.key || equal(pair.before.column.dataType, pair.after.column.dataType) && typeChange.classify(pair) === void 0) return false;
2208
+ const { after, before } = pair;
2209
+ const renamedTable = tableKey(before.table.identity) !== tableKey(after.table.identity);
2210
+ if (renamedTable && !pending.decisions.some((parent) => !("enum" in parent) && !("kind" in parent) && parent.column === void 0 && equal(parent.table, before.table.identity) && parent.candidates.some((name) => equal({
2211
+ ...parent.table,
2212
+ name
2213
+ }, after.table.identity)))) return false;
2214
+ return before.column.key === after.column.key ? renamedTable || deferred : !before.table.columns.some((column) => column.key === after.column.key) && !after.table.columns.some((column) => column.key === before.column.key);
2215
+ };
2017
2216
  const issuedForPairing = (pending, input) => pending.decisions.some((parent) => {
2217
+ if ("kind" in parent) return false;
2018
2218
  if ("enum" in parent) {
2019
2219
  const value = input.value;
2020
2220
  return parent.value === void 0 && typeof value === "string" && equal(parent.enum, input.enum) && parent.candidates.some((name) => input.id === valueId(parent.enum, {
@@ -2028,29 +2228,55 @@ const issuedForPairing = (pending, input) => pending.decisions.some((parent) =>
2028
2228
  name
2029
2229
  }, column));
2030
2230
  });
2031
- const reviewAnswers = (pending, diff, inputs, merging) => effect.Effect.gen(function* () {
2231
+ const readEnumAnswers = (document, questions, inputs) => {
2232
+ const enums = questions.filter((item) => "enum" in item);
2233
+ const expected = new Set(enums.map((item) => item.id));
2234
+ const supplied = inputs.filter((input) => record(input) && typeof input.id === "string" && expected.has(input.id));
2235
+ const ids = new Set(supplied.map((input) => input.id));
2236
+ return readAnswers({
2237
+ ...document,
2238
+ decisions: enums
2239
+ }, [...supplied, ...enums.filter((item) => !ids.has(item.id))], true);
2240
+ };
2241
+ const enumsAnswered = (decisions) => !Array.from(decisions).some((item) => "enum" in item && item.resolution.action === "pending");
2242
+ const reviewAnswers = (pending, diff, inputs, merging, typeChange) => effect.Effect.gen(function* () {
2032
2243
  const rootIds = new Set(pending.decisions.map((item) => item.id));
2033
2244
  const roots = inputs.filter((input) => record(input) && typeof input.id === "string" && rootIds.has(input.id));
2034
2245
  const rootAnswers = yield* readAnswers(pending, roots, merging);
2035
2246
  const expanded = expandRenames(diff, rootAnswers);
2247
+ const resolutions = new Map(inputs.flatMap((input) => record(input) && typeof input.id === "string" ? [[input.id, input.resolution]] : []));
2248
+ const paired = pairColumns(expanded.diff, (id) => resolutions.get(id));
2249
+ const deferred = defersTypeChanges(pending.decisions);
2250
+ let renames;
2251
+ let nestedTypeChanges = [];
2252
+ if (typeChange && deferred && enumsAnswered(rootAnswers.values())) {
2253
+ const labels = yield* effect.Effect.result(readEnumAnswers(pending, expanded.nested, inputs));
2254
+ if (effect.Result.isSuccess(labels) && enumsAnswered(labels.success.values())) {
2255
+ renames = acceptedEnumRenames(expanded.diff, new Map([...rootAnswers, ...labels.success]));
2256
+ nestedTypeChanges = typeChangeReviews(paired, pending, typeChange, "all", renames);
2257
+ }
2258
+ } else if (!deferred) nestedTypeChanges = typeChangeReviews(paired, pending, typeChange, "nested");
2259
+ const nested = [...expanded.nested, ...nestedTypeChanges.flatMap((item) => item.questions)];
2036
2260
  const review = {
2037
2261
  ...pending,
2038
- decisions: [...rootAnswers.values(), ...expanded.nested]
2262
+ decisions: [...rootAnswers.values(), ...nested]
2039
2263
  };
2040
2264
  const expected = new Set(review.decisions.map((item) => item.id));
2041
- const current = inputs.filter((input) => !merging || !record(input) || typeof input.id !== "string" || expected.has(input.id) || !issuedForPairing(pending, input));
2265
+ const current = inputs.filter((input) => !merging || !record(input) || typeof input.id !== "string" || expected.has(input.id) || !(issuedForPairing(pending, input) || typeChange && issuedForTypeChangePairing(pending, input, deferred, typeChange)));
2042
2266
  const ids = new Set(current.flatMap((input) => record(input) ? [input.id] : []));
2043
- const missing = expanded.nested.filter((item) => !ids.has(item.id));
2267
+ const missing = nested.filter((item) => !ids.has(item.id));
2044
2268
  if (!merging && missing.length) {
2045
- const required = missing.some((item) => "enum" in item) ? "Enum rename requires value decisions" : "Table rename requires column decisions";
2269
+ const required = missing.some((item) => "enum" in item) ? "Enum rename requires value decisions" : missing.some((item) => !("kind" in item)) ? "Table rename requires column decisions" : "Rename requires type-change decisions";
2046
2270
  return yield* effect.Effect.fail(new MigrationDecisionError({
2047
2271
  message: `${required}. Run --merge-decisions to review them.`,
2048
2272
  pending: review
2049
2273
  }));
2050
2274
  }
2051
2275
  return {
2052
- answers: yield* readAnswers(review, [...current, ...missing], merging),
2053
- diff: expanded.diff
2276
+ answers: yield* readAnswers(review, [...current, ...missing], merging, typeChange, renames),
2277
+ diff: expanded.diff,
2278
+ nestedTypeChanges,
2279
+ paired
2054
2280
  };
2055
2281
  });
2056
2282
  /** The enum and value renames that the reviewer accepted. */
@@ -2062,63 +2288,113 @@ const enumRenames = (diff, answers) => {
2062
2288
  const { after, before } = change;
2063
2289
  const key = tableKey(before.identity);
2064
2290
  if (change._tag === "EnumRenamed") enums.set(key, after.identity);
2065
- values.set(key, new Map(before.values.flatMap((value) => {
2291
+ const labels = new Map(before.values.flatMap((value) => {
2066
2292
  const choice = answers.get(valueId(before.identity, after.identity, value))?.resolution;
2067
2293
  return choice?.action === "rename" ? [[value, choice.target]] : [];
2068
- })));
2294
+ }));
2295
+ if (labels.size) values.set(key, labels);
2069
2296
  }
2070
2297
  return {
2071
2298
  enums,
2072
2299
  values
2073
2300
  };
2074
2301
  };
2075
- /** Refresh the questions and snapshots, carrying forward applicable reviewed choices. */
2076
- const mergeMigrationDecisions = (fresh, previous) => effect.Effect.gen(function* () {
2077
- if (!record(previous) || previous.version !== 1 || !Array.isArray(previous.decisions)) return yield* effect.Effect.fail(new MigrationDecisionError({
2078
- message: "Expected a version 1 migration decision document.",
2079
- pending: fresh
2080
- }));
2081
- const before = yield* decodeDatabaseSchema(previous.before);
2082
- const after = yield* decodeDatabaseSchema(previous.after);
2083
- const originalDiff = yield* diffDatabases(before, after);
2084
- const original = {
2085
- after,
2086
- before,
2087
- decisions: questions(originalDiff),
2088
- version: 1
2089
- };
2090
- const { answers } = yield* reviewAnswers(original, originalDiff, previous.decisions, true);
2091
- const carry = (question) => {
2092
- const resolution = answers.get(question.id)?.resolution;
2093
- if (!resolution || resolution.action === "rename" && !question.candidates.includes(resolution.target)) return question;
2302
+ const acceptedEnumRenames = (diff, answers) => {
2303
+ const renames = enumRenames(diff, answers);
2304
+ return renames.enums.size || renames.values.size ? renames : void 0;
2305
+ };
2306
+ /** Rebuild the column pair and accepted enum renames to validate a proposed fallback. */
2307
+ const validateTypeChangeFallback = (document, decision, literal, typeChange) => {
2308
+ let renames;
2309
+ if (defersTypeChanges(document.decisions)) {
2310
+ const diff = { changes: diffEnums(document.before, document.after) };
2311
+ const answers = effect.Effect.runSync(effect.Effect.result(effect.Effect.gen(function* () {
2312
+ const roots = yield* readEnumAnswers(document, questions(diff), document.decisions);
2313
+ const expanded = expandRenames(diff, roots);
2314
+ const labels = yield* readEnumAnswers(document, expanded.nested, document.decisions);
2315
+ return acceptedEnumRenames(expanded.diff, new Map([...roots, ...labels]));
2316
+ })));
2317
+ if (effect.Result.isFailure(answers)) return answers.failure.message;
2318
+ renames = answers.success;
2319
+ }
2320
+ return validateFallback(document, decision, literal, typeChange, renames);
2321
+ };
2322
+ function mergeMigrationDecisions(fresh, previous, typeChange) {
2323
+ return effect.Effect.gen(function* () {
2324
+ if (!record(previous) || previous.version !== 1 || !Array.isArray(previous.decisions)) return yield* effect.Effect.fail(new MigrationDecisionError({
2325
+ message: "Expected a version 1 migration decision document.",
2326
+ pending: fresh
2327
+ }));
2328
+ const before = yield* decodeDatabaseSchema(previous.before);
2329
+ const after = yield* decodeDatabaseSchema(previous.after);
2330
+ const originalDiff = yield* diffDatabases(before, after);
2331
+ const original = rootReview(originalDiff, before, after, typeChange).document;
2332
+ const { answers } = yield* reviewAnswers(original, originalDiff, previous.decisions, true, typeChange);
2333
+ const carry = (question, renames) => {
2334
+ const answer = answers.get(question.id);
2335
+ if (!answer) return question;
2336
+ if ("kind" in question) {
2337
+ if (!("kind" in answer)) return question;
2338
+ const resolution = answer.resolution;
2339
+ if ("fallback" in resolution && typeChange && validateFallback(fresh, question, resolution.fallback.literal, typeChange, renames) !== void 0) return question;
2340
+ return {
2341
+ ...question,
2342
+ resolution
2343
+ };
2344
+ }
2345
+ if ("kind" in answer) return question;
2346
+ const resolution = answer.resolution;
2347
+ if (resolution.action === "rename" && !question.candidates.includes(resolution.target)) return question;
2348
+ return {
2349
+ ...question,
2350
+ resolution
2351
+ };
2352
+ };
2353
+ const freshDiff = yield* diffDatabases(fresh.before, fresh.after);
2354
+ const roots = rootReview(freshDiff, fresh.before, fresh.after, typeChange).document.decisions.map((question) => carry(question));
2355
+ const expanded = expandRenames(freshDiff, new Map(roots.map((item) => [item.id, item])));
2356
+ const decisions = [...roots, ...expanded.nested.map((question) => carry(question))];
2357
+ const deferred = defersTypeChanges(roots);
2358
+ if (typeChange && (!deferred || enumsAnswered(decisions))) {
2359
+ const carried = new Map(decisions.map((item) => [item.id, item]));
2360
+ const paired = pairColumns(expanded.diff, (id) => carried.get(id)?.resolution);
2361
+ const renames = deferred ? acceptedEnumRenames(expanded.diff, carried) : void 0;
2362
+ const reviews = typeChangeReviews(paired, fresh, typeChange, deferred ? "all" : "nested", renames);
2363
+ for (const review of reviews) decisions.push(...review.questions.map((question) => carry(question, renames)));
2364
+ }
2094
2365
  return {
2095
- ...question,
2096
- resolution
2366
+ ...fresh,
2367
+ decisions
2097
2368
  };
2098
- };
2099
- const freshDiff = yield* diffDatabases(fresh.before, fresh.after);
2100
- const roots = questions(freshDiff).map(carry);
2101
- const expanded = expandRenames(freshDiff, new Map(roots.map((item) => [item.id, item])));
2369
+ });
2370
+ }
2371
+ const resolvedTypeChanges = (reviews, answers) => reviews.map(({ change: { before }, classification, questions }) => {
2372
+ let loss;
2373
+ let failure;
2374
+ for (const question of questions) {
2375
+ const resolution = answers.get(question.id)?.resolution;
2376
+ if (resolution?.action === "accept_loss" || resolution?.action === "guard") loss = resolution.action;
2377
+ else if (resolution?.action === "accept_failure") failure = { action: "accept_failure" };
2378
+ else if (resolution && "fallback" in resolution) failure = { fallback: resolution.fallback };
2379
+ }
2102
2380
  return {
2103
- ...fresh,
2104
- decisions: [...roots, ...expanded.nested.map(carry)]
2381
+ classification,
2382
+ column: before.column.name,
2383
+ table: before.table.identity,
2384
+ ...loss ? { loss } : {},
2385
+ ...failure ? { failure } : {}
2105
2386
  };
2106
2387
  });
2107
2388
  /** Validate untrusted JSON and resolve intent against fresh comparison results. */
2108
- const resolveMigrationDecisions = (before, after, supplied) => effect.Effect.gen(function* () {
2389
+ const resolveMigrationDecisions = (before, after, supplied, typeChange) => effect.Effect.gen(function* () {
2109
2390
  const diff = yield* diffDatabases(before, after);
2110
- const pending = {
2111
- after,
2112
- before,
2113
- decisions: questions(diff),
2114
- version: 1
2115
- };
2391
+ const { document: pending, typeChanges: roots } = rootReview(diff, before, after, typeChange);
2116
2392
  const fail = (message) => effect.Effect.fail(new MigrationDecisionError({
2117
2393
  message,
2118
2394
  pending
2119
2395
  }));
2120
2396
  if (supplied === void 0) {
2121
- if (pending.decisions.length) return yield* fail("Unresolved migration decisions. Prepare a decision file and resolve each removal before planning.");
2397
+ if (pending.decisions.length) return yield* fail(roots.length ? "Unresolved migration decisions. Prepare a decision file and resolve each question before planning." : "Unresolved migration decisions. Prepare a decision file and resolve each removal before planning.");
2122
2398
  return {
2123
2399
  decisions: pending,
2124
2400
  diff
@@ -2126,42 +2402,19 @@ const resolveMigrationDecisions = (before, after, supplied) => effect.Effect.gen
2126
2402
  }
2127
2403
  if (!record(supplied) || supplied.version !== 1 || !Array.isArray(supplied.decisions)) return yield* fail("Expected a version 1 migration decision document.");
2128
2404
  if (!equal(supplied.before, before) || !equal(supplied.after, after)) return yield* fail("Stale migration decisions: source or target schema changed. Prepare a new decision file.");
2129
- const reviewed = yield* reviewAnswers(pending, diff, supplied.decisions, false);
2405
+ const reviewed = yield* reviewAnswers(pending, diff, supplied.decisions, false, typeChange);
2130
2406
  const answers = reviewed.answers;
2407
+ const typeChanges = resolvedTypeChanges([...roots, ...reviewed.nestedTypeChanges], answers);
2131
2408
  const dropGuards = [];
2132
- const changes = reviewed.diff.changes.map((change) => {
2133
- if (!("changes" in change)) {
2134
- if (change._tag === "TableRemoved" && answers.get(idFor(change.table))?.resolution.action === "drop_if_empty") dropGuards.push({ table: change.table });
2135
- return change;
2136
- }
2137
- const renamedTargets = /* @__PURE__ */ new Set();
2138
- const changes = [];
2139
- for (const item of change.changes) {
2140
- if (item._tag !== "ColumnRemoved") continue;
2141
- const answer = answers.get(columnId(change, item.column.key));
2142
- if (answer.resolution.action === "drop_if_empty") dropGuards.push({
2143
- column: item.column.name,
2144
- table: change.table
2145
- });
2146
- if (answer.resolution.action !== "rename") continue;
2147
- const targetKey = answer.resolution.target;
2148
- const afterColumn = change.after.columns.find((column) => column.key === targetKey);
2149
- renamedTargets.add(afterColumn.key);
2150
- const fields = [];
2151
- if (!equal(item.column.dataType, afterColumn.dataType)) fields.push("dataType");
2152
- if (!constraintsEqual(item.column.constraints, afterColumn.constraints)) fields.push("constraints");
2153
- changes.push({
2154
- _tag: "ColumnRenamed",
2155
- after: afterColumn,
2156
- before: item.column,
2157
- fields
2158
- });
2159
- }
2160
- return {
2161
- ...change,
2162
- changes: [...changes, ...change.changes.filter((item) => !(item._tag === "ColumnAdded" && renamedTargets.has(item.column.key)) && !(item._tag === "ColumnRemoved" && answers.get(columnId(change, item.column.key))?.resolution.action === "rename"))]
2163
- };
2164
- });
2409
+ for (const change of reviewed.diff.changes) {
2410
+ if (change._tag === "TableRemoved" && answers.get(idFor(change.table))?.resolution.action === "drop_if_empty") dropGuards.push({ table: change.table });
2411
+ if (!("changes" in change)) continue;
2412
+ for (const item of change.changes) if (item._tag === "ColumnRemoved" && answers.get(columnId(change, item.column.key))?.resolution.action === "drop_if_empty") dropGuards.push({
2413
+ column: item.column.name,
2414
+ table: change.table
2415
+ });
2416
+ }
2417
+ const { changes } = reviewed.paired;
2165
2418
  const renames = sequenceRenames(changes);
2166
2419
  const kept = changes.filter((change) => !/^(Comment|Enum|Sequence|Trigger)/.test(change._tag));
2167
2420
  const leading = (change) => /^(Namespace|Extension)/.test(change._tag);
@@ -2174,7 +2427,8 @@ const resolveMigrationDecisions = (before, after, supplied) => effect.Effect.gen
2174
2427
  ];
2175
2428
  const resolved = {
2176
2429
  changes: [...withRenames, ...diffComments(before, after, withRenames)],
2177
- ...dropGuards.length ? { dropGuards } : {}
2430
+ ...dropGuards.length ? { dropGuards } : {},
2431
+ ...typeChanges.length ? { typeChanges } : {}
2178
2432
  };
2179
2433
  return {
2180
2434
  decisions: {
@@ -2310,6 +2564,17 @@ const mappingResult = effect.Schema.Struct({
2310
2564
  diagnostics,
2311
2565
  schema: effect.Schema.Unknown
2312
2566
  });
2567
+ const stringList = effect.Schema.Array(effect.Schema.String);
2568
+ const mapperSubjectDescriptionSchema = effect.Schema.Struct({
2569
+ definitions: effect.Schema.optionalKey(stringList),
2570
+ language: effect.Schema.NonEmptyString,
2571
+ notes: effect.Schema.optionalKey(stringList),
2572
+ types: effect.Schema.Array(effect.Schema.Struct({
2573
+ label: effect.Schema.NonEmptyString,
2574
+ text: effect.Schema.String
2575
+ }))
2576
+ });
2577
+ const subjectDescription = effect.Schema.UndefinedOr(mapperSubjectDescriptionSchema);
2313
2578
  const wrapError = (cause, code, path, fallback) => {
2314
2579
  if (cause instanceof CodegenError) return cause;
2315
2580
  const details = effect.Schema.decodeUnknownOption(taggedCodegenError)(cause);
@@ -2366,6 +2631,39 @@ const invoke = (callback, code, path) => effect.Effect.flatMap(validate(() => {
2366
2631
  });
2367
2632
  return result;
2368
2633
  }, "invalid-plugin", path), (effect$1) => effect.Effect.mapError(effect$1, (cause) => wrapError(cause, code, path, `Plugin ${path}() failed`)));
2634
+ /** Optional capability: absent gives no describer; a present value must be a function. */
2635
+ const optionalDescribe = (plugin) => {
2636
+ if (!("describe" in plugin)) return;
2637
+ const callback = plugin.describe;
2638
+ if (typeof callback !== "function") throw new CodegenError({
2639
+ code: "invalid-plugin",
2640
+ message: "Plugin describe() must be a function",
2641
+ path: "describe"
2642
+ });
2643
+ return (schema, subject) => {
2644
+ let result;
2645
+ try {
2646
+ result = Reflect.apply(callback, plugin, [schema, subject]);
2647
+ } catch (cause) {
2648
+ throw new CodegenError({
2649
+ cause,
2650
+ code: "description-failed",
2651
+ message: cause instanceof Error ? cause.message : "Plugin describe() failed",
2652
+ path: "describe"
2653
+ });
2654
+ }
2655
+ try {
2656
+ return effect.Schema.decodeUnknownSync(subjectDescription)(result);
2657
+ } catch (cause) {
2658
+ throw new CodegenError({
2659
+ cause,
2660
+ code: "invalid-description",
2661
+ message: "Plugin describe() returned an invalid subject description",
2662
+ path: "describe"
2663
+ });
2664
+ }
2665
+ };
2666
+ };
2369
2667
  /** Validate the mapper value selected from a module by the consumer. */
2370
2668
  const decodeMapperPlugin = (value) => validate(() => {
2371
2669
  const plugin = readExport(value, "mapper");
@@ -2373,8 +2671,10 @@ const decodeMapperPlugin = (value) => validate(() => {
2373
2671
  const decodeInput = method(plugin, "decodeInput");
2374
2672
  const decodeOptions = method(plugin, "decodeOptions");
2375
2673
  const map = method(plugin, "map");
2674
+ const describeSubject = optionalDescribe(plugin);
2376
2675
  return {
2377
2676
  descriptor,
2677
+ ...describeSubject === void 0 ? {} : { describe: describeSubject },
2378
2678
  map: (schema, options) => effect.Effect.gen(function* () {
2379
2679
  const input = yield* invoke(() => decodeInput(schema), "invalid-input", "decodeInput");
2380
2680
  const settings = yield* invoke(() => decodeOptions(options), "invalid-options", "decodeOptions");
@@ -2401,6 +2701,38 @@ const decodeGeneratorPlugin = (value) => validate(() => {
2401
2701
  })
2402
2702
  };
2403
2703
  }, "invalid-plugin", "generator");
2704
+ // src/codegen-pipeline.ts
2705
+ /** Map every profile in order, retaining errors and diagnostics for the caller. */
2706
+ const mapProfiles = (schema, profiles) => effect.Effect.forEach(profiles, ({ mapper, name, options }) => mapper.map(schema, options).pipe(effect.Effect.match({
2707
+ onFailure: (error) => ({
2708
+ mapper,
2709
+ name,
2710
+ result: { error }
2711
+ }),
2712
+ onSuccess: (result) => ({
2713
+ mapper,
2714
+ name,
2715
+ result
2716
+ })
2717
+ })));
2718
+ var GenerationFailure = class extends effect.Data.TaggedError("GenerationFailure") {};
2719
+ /** Check the entire batch's contracts before invoking any generator. */
2720
+ const generate = (mapped, generators) => effect.Effect.gen(function* () {
2721
+ const output = mapped.mapper.descriptor.output;
2722
+ yield* effect.Effect.forEach(generators, ({ generator, name }) => validateApplicationCompatibility(output, generator.descriptor.input).pipe(effect.Effect.mapError((error) => new GenerationFailure({
2723
+ error,
2724
+ generator: name,
2725
+ stage: "compatibility"
2726
+ }))), { discard: true });
2727
+ return yield* effect.Effect.forEach(generators, ({ generator, name, options }) => generator.generate(output, mapped.result.schema, options).pipe(effect.Effect.mapError((error) => new GenerationFailure({
2728
+ error,
2729
+ generator: name,
2730
+ stage: "generation"
2731
+ })), effect.Effect.map((result) => ({
2732
+ name,
2733
+ result
2734
+ }))));
2735
+ });
2404
2736
  exports.CodegenError = CodegenError;
2405
2737
  exports.MigrationDecisionError = MigrationDecisionError;
2406
2738
  exports.SchemaDiffError = SchemaDiffError;
@@ -2434,14 +2766,17 @@ exports.externalObjects = externalObjects;
2434
2766
  exports.formatExtractOmissions = formatExtractOmissions;
2435
2767
  exports.functionKey = functionKey;
2436
2768
  exports.functionLabel = functionLabel;
2769
+ exports.generate = generate;
2437
2770
  exports.generatedFileHeader = generatedFileHeader;
2438
2771
  exports.hashMigrationPair = hashMigrationPair;
2772
+ exports.mapProfiles = mapProfiles;
2439
2773
  exports.mergeMigrationDecisions = mergeMigrationDecisions;
2440
2774
  exports.migrationRun = migrationRun;
2441
2775
  exports.nameSpan = nameSpan;
2442
2776
  exports.namespaceKey = namespaceKey;
2443
2777
  exports.namespaceOf = namespaceOf;
2444
2778
  exports.nextMigration = nextMigration;
2779
+ exports.pairedColumns = pairedColumns;
2445
2780
  exports.planDatabaseMigration = planDatabaseMigration;
2446
2781
  exports.planDownMigration = planDownMigration;
2447
2782
  exports.prepareMigrationDecisions = prepareMigrationDecisions;
@@ -2457,3 +2792,4 @@ exports.tableKey = tableKey;
2457
2792
  exports.triggerKey = triggerKey;
2458
2793
  exports.validateApplicationCompatibility = validateApplicationCompatibility;
2459
2794
  exports.validateDatabase = validateDatabase;
2795
+ exports.validateTypeChangeFallback = validateTypeChangeFallback;