2.0 KiB
checksum
(no submodules)
Purpose
Provides SHA-256 checksum utilities for the migration package. The checksum system detects when a migration's source has been modified after it was applied to a database, preventing accidental schema drift from silent SQL edits. Using node:crypto directly avoids introducing a dependency on @suaveplan/crypto-hash, keeping the migration package's dependency graph minimal.
Features
computeChecksum(content)— returns the SHA-256 hex digest of any string.checksumMigration(up)— serialises a migration'supfunction to its source string and hashes it.
Usage: Basic Example
import { computeChecksum } from "@suaveplan/migration";
const hash = computeChecksum("CREATE TABLE users (id TEXT PRIMARY KEY)");
// "a4c2f..." (64-char hex string)
Usage: Advanced Example
import { checksumMigration } from "@suaveplan/migration";
async function validateChecksums(migrations, appliedRecords) {
for (const migration of migrations) {
const record = appliedRecords.find(r => r.id === migration.id);
if (!record?.checksum) continue;
const computed = checksumMigration(migration.up);
if (computed !== record.checksum) {
throw new Error(`Checksum mismatch for ${migration.id}`);
}
}
}
API Reference
computeChecksum(content: string): string
Returns the lowercase hex SHA-256 digest of content. Uses node:crypto synchronously.
checksumMigration(up: (ctx: unknown) => Promise<void>): string
Calls up.toString() to obtain the function source and passes it to computeChecksum. The result is deterministic for a given function body.
Implementation Notes
Function.prototype.toString() is mandated by the ECMAScript specification to return the original source text (or a representation of it). In practice, transpilers and minifiers may change function bodies; for best reliability, checksums should be computed from source-file content in a pre-commit hook rather than at runtime in production builds.