@prisma-next/migration-tools 0.0.1
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 +88 -0
- package/dist/errors-DdSjGRqx.mjs +115 -0
- package/dist/errors-DdSjGRqx.mjs.map +1 -0
- package/dist/exports/attestation.d.mts +15 -0
- package/dist/exports/attestation.d.mts.map +1 -0
- package/dist/exports/attestation.mjs +65 -0
- package/dist/exports/attestation.mjs.map +1 -0
- package/dist/exports/dag.d.mts +30 -0
- package/dist/exports/dag.d.mts.map +1 -0
- package/dist/exports/dag.mjs +182 -0
- package/dist/exports/dag.mjs.map +1 -0
- package/dist/exports/io.d.mts +10 -0
- package/dist/exports/io.d.mts.map +1 -0
- package/dist/exports/io.mjs +3 -0
- package/dist/exports/types.d.mts +35 -0
- package/dist/exports/types.d.mts.map +1 -0
- package/dist/exports/types.mjs +3 -0
- package/dist/io-Dx98-h0p.mjs +131 -0
- package/dist/io-Dx98-h0p.mjs.map +1 -0
- package/dist/types-CUnzoaLY.d.mts +56 -0
- package/dist/types-CUnzoaLY.d.mts.map +1 -0
- package/package.json +62 -0
- package/src/attestation.ts +76 -0
- package/src/canonicalize-json.ts +17 -0
- package/src/dag.ts +280 -0
- package/src/errors.ts +121 -0
- package/src/exports/attestation.ts +1 -0
- package/src/exports/dag.ts +8 -0
- package/src/exports/io.ts +6 -0
- package/src/exports/types.ts +9 -0
- package/src/io.ts +197 -0
- package/src/types.ts +51 -0
package/src/errors.ts
ADDED
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Structured error for migration tooling operations.
|
|
3
|
+
*
|
|
4
|
+
* Follows the NAMESPACE.SUBCODE convention from ADR 027. All codes live under
|
|
5
|
+
* the MIGRATION namespace. These are tooling-time errors (file I/O, attestation,
|
|
6
|
+
* migration-chain reconstruction), distinct from the runtime MIGRATION.* codes for apply-time
|
|
7
|
+
* failures (PRECHECK_FAILED, POSTCHECK_FAILED, etc.).
|
|
8
|
+
*
|
|
9
|
+
* Fields:
|
|
10
|
+
* - code: Stable machine-readable code (MIGRATION.SUBCODE)
|
|
11
|
+
* - category: Always 'MIGRATION'
|
|
12
|
+
* - why: Explains the cause in plain language
|
|
13
|
+
* - fix: Actionable remediation step
|
|
14
|
+
* - details: Machine-readable structured data for agents
|
|
15
|
+
*/
|
|
16
|
+
export class MigrationToolsError extends Error {
|
|
17
|
+
readonly code: string;
|
|
18
|
+
readonly category = 'MIGRATION' as const;
|
|
19
|
+
readonly why: string;
|
|
20
|
+
readonly fix: string;
|
|
21
|
+
readonly details: Record<string, unknown> | undefined;
|
|
22
|
+
|
|
23
|
+
constructor(
|
|
24
|
+
code: string,
|
|
25
|
+
summary: string,
|
|
26
|
+
options: {
|
|
27
|
+
readonly why: string;
|
|
28
|
+
readonly fix: string;
|
|
29
|
+
readonly details?: Record<string, unknown>;
|
|
30
|
+
},
|
|
31
|
+
) {
|
|
32
|
+
super(summary);
|
|
33
|
+
this.name = 'MigrationToolsError';
|
|
34
|
+
this.code = code;
|
|
35
|
+
this.why = options.why;
|
|
36
|
+
this.fix = options.fix;
|
|
37
|
+
this.details = options.details;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
static is(error: unknown): error is MigrationToolsError {
|
|
41
|
+
if (!(error instanceof Error)) return false;
|
|
42
|
+
const candidate = error as MigrationToolsError;
|
|
43
|
+
return candidate.name === 'MigrationToolsError' && typeof candidate.code === 'string';
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
export function errorDirectoryExists(dir: string): MigrationToolsError {
|
|
48
|
+
return new MigrationToolsError('MIGRATION.DIR_EXISTS', 'Migration directory already exists', {
|
|
49
|
+
why: `The directory "${dir}" already exists. Each migration must have a unique directory.`,
|
|
50
|
+
fix: 'Use --name to pick a different name, or delete the existing directory and re-run.',
|
|
51
|
+
details: { dir },
|
|
52
|
+
});
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
export function errorMissingFile(file: string, dir: string): MigrationToolsError {
|
|
56
|
+
return new MigrationToolsError('MIGRATION.FILE_MISSING', `Missing ${file}`, {
|
|
57
|
+
why: `Expected "${file}" in "${dir}" but the file does not exist.`,
|
|
58
|
+
fix: 'Ensure the migration directory contains both migration.json and ops.json. If the directory is corrupt, delete it and re-run migration plan.',
|
|
59
|
+
details: { file, dir },
|
|
60
|
+
});
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
export function errorInvalidJson(filePath: string, parseError: string): MigrationToolsError {
|
|
64
|
+
return new MigrationToolsError('MIGRATION.INVALID_JSON', 'Invalid JSON in migration file', {
|
|
65
|
+
why: `Failed to parse "${filePath}": ${parseError}`,
|
|
66
|
+
fix: 'Fix the JSON syntax error, or delete the migration directory and re-run migration plan.',
|
|
67
|
+
details: { filePath, parseError },
|
|
68
|
+
});
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
export function errorInvalidManifest(filePath: string, reason: string): MigrationToolsError {
|
|
72
|
+
return new MigrationToolsError('MIGRATION.INVALID_MANIFEST', 'Invalid migration manifest', {
|
|
73
|
+
why: `Manifest at "${filePath}" is invalid: ${reason}`,
|
|
74
|
+
fix: 'Ensure the manifest has all required fields (from, to, kind, toContract). If corrupt, delete and re-plan.',
|
|
75
|
+
details: { filePath, reason },
|
|
76
|
+
});
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
export function errorInvalidSlug(slug: string): MigrationToolsError {
|
|
80
|
+
return new MigrationToolsError('MIGRATION.INVALID_NAME', 'Invalid migration name', {
|
|
81
|
+
why: `The slug "${slug}" contains no valid characters after sanitization (only a-z, 0-9 are kept).`,
|
|
82
|
+
fix: 'Provide a name with at least one alphanumeric character, e.g. --name add_users.',
|
|
83
|
+
details: { slug },
|
|
84
|
+
});
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
export function errorSelfLoop(dirName: string, hash: string): MigrationToolsError {
|
|
88
|
+
return new MigrationToolsError('MIGRATION.SELF_LOOP', 'Self-loop in migration graph', {
|
|
89
|
+
why: `Migration "${dirName}" has from === to === "${hash}". A migration must transition between two different contract states.`,
|
|
90
|
+
fix: 'Delete the invalid migration directory and re-run migration plan.',
|
|
91
|
+
details: { dirName, hash },
|
|
92
|
+
});
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
export function errorAmbiguousLeaf(leaves: readonly string[]): MigrationToolsError {
|
|
96
|
+
return new MigrationToolsError('MIGRATION.AMBIGUOUS_LEAF', 'Ambiguous migration graph', {
|
|
97
|
+
why: `Multiple leaf nodes found: ${leaves.join(', ')}. The migration graph has diverged — this typically happens when two developers plan migrations from the same starting point.`,
|
|
98
|
+
fix: 'Delete one of the conflicting migration directories, then re-run `migration plan` to re-plan it from the remaining branch. Or use --from <hash> to explicitly select a starting point.',
|
|
99
|
+
details: { leaves },
|
|
100
|
+
});
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
export function errorNoRoot(nodes: readonly string[]): MigrationToolsError {
|
|
104
|
+
return new MigrationToolsError('MIGRATION.NO_ROOT', 'Migration graph has no root', {
|
|
105
|
+
why: `No root migration found in the migration graph (nodes: ${nodes.join(', ')}). Every migration references a parentMigrationId that does not exist, or the graph contains a cycle in parent pointers.`,
|
|
106
|
+
fix: 'Inspect the migrations directory for corrupted migration.json files. Exactly one migration must have parentMigrationId set to null (the first migration).',
|
|
107
|
+
details: { nodes },
|
|
108
|
+
});
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
export function errorDuplicateMigrationId(migrationId: string): MigrationToolsError {
|
|
112
|
+
return new MigrationToolsError(
|
|
113
|
+
'MIGRATION.DUPLICATE_MIGRATION_ID',
|
|
114
|
+
'Duplicate migrationId in migration graph',
|
|
115
|
+
{
|
|
116
|
+
why: `Multiple migrations share migrationId "${migrationId}". This makes parent-chain reconstruction ambiguous and unsafe.`,
|
|
117
|
+
fix: 'Regenerate one of the conflicting migrations so each migrationId is unique, then re-run migration commands.',
|
|
118
|
+
details: { migrationId },
|
|
119
|
+
},
|
|
120
|
+
);
|
|
121
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export { attestMigration, computeMigrationId, verifyMigration } from '../attestation';
|
package/src/io.ts
ADDED
|
@@ -0,0 +1,197 @@
|
|
|
1
|
+
import { mkdir, readdir, readFile, stat, writeFile } from 'node:fs/promises';
|
|
2
|
+
import { type } from 'arktype';
|
|
3
|
+
import { basename, dirname, join } from 'pathe';
|
|
4
|
+
import {
|
|
5
|
+
errorDirectoryExists,
|
|
6
|
+
errorInvalidJson,
|
|
7
|
+
errorInvalidManifest,
|
|
8
|
+
errorInvalidSlug,
|
|
9
|
+
errorMissingFile,
|
|
10
|
+
} from './errors';
|
|
11
|
+
import type { MigrationManifest, MigrationOps, MigrationPackage } from './types';
|
|
12
|
+
|
|
13
|
+
const MANIFEST_FILE = 'migration.json';
|
|
14
|
+
const OPS_FILE = 'ops.json';
|
|
15
|
+
const MAX_SLUG_LENGTH = 64;
|
|
16
|
+
|
|
17
|
+
function hasErrnoCode(error: unknown, code: string): boolean {
|
|
18
|
+
return error instanceof Error && (error as { code?: string }).code === code;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
const MigrationHintsSchema = type({
|
|
22
|
+
used: 'string[]',
|
|
23
|
+
applied: 'string[]',
|
|
24
|
+
plannerVersion: 'string',
|
|
25
|
+
planningStrategy: 'string',
|
|
26
|
+
});
|
|
27
|
+
|
|
28
|
+
const MigrationManifestSchema = type({
|
|
29
|
+
from: 'string',
|
|
30
|
+
to: 'string',
|
|
31
|
+
migrationId: 'string | null',
|
|
32
|
+
parentMigrationId: 'string | null',
|
|
33
|
+
kind: "'regular' | 'baseline'",
|
|
34
|
+
fromContract: 'object | null',
|
|
35
|
+
toContract: 'object',
|
|
36
|
+
hints: MigrationHintsSchema,
|
|
37
|
+
labels: 'string[]',
|
|
38
|
+
'authorship?': type({
|
|
39
|
+
'author?': 'string',
|
|
40
|
+
'email?': 'string',
|
|
41
|
+
}),
|
|
42
|
+
'signature?': type({
|
|
43
|
+
keyId: 'string',
|
|
44
|
+
value: 'string',
|
|
45
|
+
}).or('null'),
|
|
46
|
+
createdAt: 'string',
|
|
47
|
+
});
|
|
48
|
+
|
|
49
|
+
const MigrationOpSchema = type({
|
|
50
|
+
id: 'string',
|
|
51
|
+
label: 'string',
|
|
52
|
+
operationClass: "'additive' | 'widening' | 'destructive'",
|
|
53
|
+
});
|
|
54
|
+
|
|
55
|
+
// Intentionally shallow: operation-specific payload validation is owned by planner/runner layers.
|
|
56
|
+
const MigrationOpsSchema = MigrationOpSchema.array();
|
|
57
|
+
|
|
58
|
+
export async function writeMigrationPackage(
|
|
59
|
+
dir: string,
|
|
60
|
+
manifest: MigrationManifest,
|
|
61
|
+
ops: MigrationOps,
|
|
62
|
+
): Promise<void> {
|
|
63
|
+
await mkdir(dirname(dir), { recursive: true });
|
|
64
|
+
|
|
65
|
+
try {
|
|
66
|
+
await mkdir(dir);
|
|
67
|
+
} catch (error) {
|
|
68
|
+
if (hasErrnoCode(error, 'EEXIST')) {
|
|
69
|
+
throw errorDirectoryExists(dir);
|
|
70
|
+
}
|
|
71
|
+
throw error;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
await writeFile(join(dir, MANIFEST_FILE), JSON.stringify(manifest, null, 2), { flag: 'wx' });
|
|
75
|
+
await writeFile(join(dir, OPS_FILE), JSON.stringify(ops, null, 2), { flag: 'wx' });
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
export async function readMigrationPackage(dir: string): Promise<MigrationPackage> {
|
|
79
|
+
const manifestPath = join(dir, MANIFEST_FILE);
|
|
80
|
+
const opsPath = join(dir, OPS_FILE);
|
|
81
|
+
|
|
82
|
+
let manifestRaw: string;
|
|
83
|
+
try {
|
|
84
|
+
manifestRaw = await readFile(manifestPath, 'utf-8');
|
|
85
|
+
} catch (error) {
|
|
86
|
+
if (hasErrnoCode(error, 'ENOENT')) {
|
|
87
|
+
throw errorMissingFile(MANIFEST_FILE, dir);
|
|
88
|
+
}
|
|
89
|
+
throw error;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
let opsRaw: string;
|
|
93
|
+
try {
|
|
94
|
+
opsRaw = await readFile(opsPath, 'utf-8');
|
|
95
|
+
} catch (error) {
|
|
96
|
+
if (hasErrnoCode(error, 'ENOENT')) {
|
|
97
|
+
throw errorMissingFile(OPS_FILE, dir);
|
|
98
|
+
}
|
|
99
|
+
throw error;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
let manifest: MigrationManifest;
|
|
103
|
+
try {
|
|
104
|
+
manifest = JSON.parse(manifestRaw);
|
|
105
|
+
} catch (e) {
|
|
106
|
+
throw errorInvalidJson(manifestPath, e instanceof Error ? e.message : String(e));
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
let ops: MigrationOps;
|
|
110
|
+
try {
|
|
111
|
+
ops = JSON.parse(opsRaw);
|
|
112
|
+
} catch (e) {
|
|
113
|
+
throw errorInvalidJson(opsPath, e instanceof Error ? e.message : String(e));
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
validateManifest(manifest, manifestPath);
|
|
117
|
+
validateOps(ops, opsPath);
|
|
118
|
+
|
|
119
|
+
return {
|
|
120
|
+
dirName: basename(dir),
|
|
121
|
+
dirPath: dir,
|
|
122
|
+
manifest,
|
|
123
|
+
ops,
|
|
124
|
+
};
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
function validateManifest(
|
|
128
|
+
manifest: unknown,
|
|
129
|
+
filePath: string,
|
|
130
|
+
): asserts manifest is MigrationManifest {
|
|
131
|
+
const result = MigrationManifestSchema(manifest);
|
|
132
|
+
if (result instanceof type.errors) {
|
|
133
|
+
throw errorInvalidManifest(filePath, result.summary);
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
function validateOps(ops: unknown, filePath: string): asserts ops is MigrationOps {
|
|
138
|
+
const result = MigrationOpsSchema(ops);
|
|
139
|
+
if (result instanceof type.errors) {
|
|
140
|
+
throw errorInvalidManifest(filePath, result.summary);
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
export async function readMigrationsDir(
|
|
145
|
+
migrationsRoot: string,
|
|
146
|
+
): Promise<readonly MigrationPackage[]> {
|
|
147
|
+
let entries: string[];
|
|
148
|
+
try {
|
|
149
|
+
entries = await readdir(migrationsRoot);
|
|
150
|
+
} catch (error) {
|
|
151
|
+
if (hasErrnoCode(error, 'ENOENT')) {
|
|
152
|
+
return [];
|
|
153
|
+
}
|
|
154
|
+
throw error;
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
const packages: MigrationPackage[] = [];
|
|
158
|
+
|
|
159
|
+
for (const entry of entries.sort()) {
|
|
160
|
+
const entryPath = join(migrationsRoot, entry);
|
|
161
|
+
const entryStat = await stat(entryPath);
|
|
162
|
+
if (!entryStat.isDirectory()) continue;
|
|
163
|
+
|
|
164
|
+
const manifestPath = join(entryPath, MANIFEST_FILE);
|
|
165
|
+
try {
|
|
166
|
+
await stat(manifestPath);
|
|
167
|
+
} catch {
|
|
168
|
+
continue; // skip non-migration directories
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
packages.push(await readMigrationPackage(entryPath));
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
return packages;
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
export function formatMigrationDirName(timestamp: Date, slug: string): string {
|
|
178
|
+
const sanitized = slug
|
|
179
|
+
.toLowerCase()
|
|
180
|
+
.replace(/[^a-z0-9]/g, '_')
|
|
181
|
+
.replace(/_+/g, '_')
|
|
182
|
+
.replace(/^_|_$/g, '');
|
|
183
|
+
|
|
184
|
+
if (sanitized.length === 0) {
|
|
185
|
+
throw errorInvalidSlug(slug);
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
const truncated = sanitized.slice(0, MAX_SLUG_LENGTH);
|
|
189
|
+
|
|
190
|
+
const y = timestamp.getUTCFullYear();
|
|
191
|
+
const mo = String(timestamp.getUTCMonth() + 1).padStart(2, '0');
|
|
192
|
+
const d = String(timestamp.getUTCDate()).padStart(2, '0');
|
|
193
|
+
const h = String(timestamp.getUTCHours()).padStart(2, '0');
|
|
194
|
+
const mi = String(timestamp.getUTCMinutes()).padStart(2, '0');
|
|
195
|
+
|
|
196
|
+
return `${y}${mo}${d}T${h}${mi}_${truncated}`;
|
|
197
|
+
}
|
package/src/types.ts
ADDED
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
import type { ContractIR } from '@prisma-next/contract/ir';
|
|
2
|
+
import type { MigrationPlanOperation } from '@prisma-next/core-control-plane/types';
|
|
3
|
+
|
|
4
|
+
export interface MigrationHints {
|
|
5
|
+
readonly used: readonly string[];
|
|
6
|
+
readonly applied: readonly string[];
|
|
7
|
+
readonly plannerVersion: string;
|
|
8
|
+
readonly planningStrategy: string;
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
export interface MigrationManifest {
|
|
12
|
+
readonly from: string;
|
|
13
|
+
readonly to: string;
|
|
14
|
+
readonly migrationId: string | null;
|
|
15
|
+
readonly parentMigrationId: string | null;
|
|
16
|
+
readonly kind: 'regular' | 'baseline';
|
|
17
|
+
readonly fromContract: ContractIR | null;
|
|
18
|
+
readonly toContract: ContractIR;
|
|
19
|
+
readonly hints: MigrationHints;
|
|
20
|
+
readonly labels: readonly string[];
|
|
21
|
+
readonly authorship?: { readonly author?: string; readonly email?: string };
|
|
22
|
+
readonly signature?: { readonly keyId: string; readonly value: string } | null;
|
|
23
|
+
readonly createdAt: string;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export type MigrationOps = readonly MigrationPlanOperation[];
|
|
27
|
+
|
|
28
|
+
export interface MigrationPackage {
|
|
29
|
+
readonly dirName: string;
|
|
30
|
+
readonly dirPath: string;
|
|
31
|
+
readonly manifest: MigrationManifest;
|
|
32
|
+
readonly ops: MigrationOps;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export interface MigrationChainEntry {
|
|
36
|
+
readonly from: string;
|
|
37
|
+
readonly to: string;
|
|
38
|
+
readonly migrationId: string | null;
|
|
39
|
+
readonly parentMigrationId: string | null;
|
|
40
|
+
readonly dirName: string;
|
|
41
|
+
readonly createdAt: string;
|
|
42
|
+
readonly labels: readonly string[];
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
export interface MigrationGraph {
|
|
46
|
+
readonly nodes: ReadonlySet<string>;
|
|
47
|
+
readonly forwardChain: ReadonlyMap<string, readonly MigrationChainEntry[]>;
|
|
48
|
+
readonly reverseChain: ReadonlyMap<string, readonly MigrationChainEntry[]>;
|
|
49
|
+
readonly migrationById: ReadonlyMap<string, MigrationChainEntry>;
|
|
50
|
+
readonly childrenByParentId: ReadonlyMap<string | null, readonly MigrationChainEntry[]>;
|
|
51
|
+
}
|